遍歷對象和數組

後臺給的數據格式不肯定,多是數組也多是對象,須要前端本身作處理,最後解決辦法以下:$.each()javascript


栗子代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
    var arr = ['av1.jpg', 'av2.jpg', 'av3.jpg']
      , obj = {pic1: 'av1.jpg', pic2: 'av2.jpg', pic3: 'av3.jpg'}
    $.each(arr, function (i, t) {
      console.log(i, t)
    })
    $.each(obj, function (i, t) {
      console.log(i, t)
    })
</script>
</body>
</html>

解決問題的時候,也想了其餘集中辦法,好比Array.prototype.map.call(arr, fn)、for(var val of)、for(var key in)、Array.from(arr, fn)css

Es5的for in能夠遍歷數組和對象的索引,arr[key], obj[key]可以取到每項的值,適合
Es6的for of能夠遍歷數組類數組對象的值,不適合
Es6的Array.from能夠遍歷類數組對象的值,不適合html

相關文章
相關標籤/搜索