js數組遍歷總結

js中的數組遍歷是項目中常常用到的,在這裏將幾種方法作個對比。前端

for循環:使用評率最高,也是最基本的一種遍歷方式。

let arr = ['a','b','c','d','e'];
for (let i = 0, len = arr.length; i < len; i++) {
    console.log(i);       //  0 1 2 3 4
    console.log(arr[i]);  //a b c d e
}

forEach()循環:forEach中傳入要執行的回調函數,函數有三個參數。第一個參數爲數組元素(必選),第二個參數爲數組元素索引值(可選),第三個參數爲數組自己(可選)

let arr = ['a','b','c','d','e'];
arr.forEach((item,index,arr)=> {
    console.log(item);   // a b c d e 
    console.log(index);  // 0 1 2 3 4
    console.log(arr);    // ['a','b','c','d','e']
})

map循環: map()中傳入要執行的回調函數,函數有三個參數。第一個參數爲數組元素(必選),第二個參數爲數組元素索引值(可選),第三個參數爲數組自己(可選)

var arr = [
    {name:'a',age:'18'},
    {name:'b',age:'19'},
    {name:'c',age:'20'}
];
arr.map(function(item,index) {
    if(item.name == 'b') {
        console.log(index)  // 1
    }
})

for...in循環:for...in循環可用於循環對象和數組,推薦用於循環對象,能夠用來遍歷json

let obj = {
    name: '王大錘',
    age: '18',
    weight: '70kg'
}
for(var key in obj) {
    console.log(key);       //  name age weight
    console.log(obj[key]);  //  王大錘 18 70kg
}
let arr = ['a','b','c','d','e'];
for(var key in arr) {
    console.log(key);  //  0 1 2 3 4 返回數組索引
    console.log(arr[key]) //  a b c d e
}

for...of循環:可循環數組和對象,推薦用於遍歷數組。

for...of提供了三個新方法:json

  1. key()是對鍵名的遍歷;
  2. value()是對鍵值的遍歷;
  3. entries()是對鍵值對的遍歷;
let arr = ['科大訊飛', '政法BG', '前端開發'];
for (let item of arr) {  
  console.log(item); //  科大訊飛  政法BG  前端開發
}
// 輸出數組索引
for (let item of arr.keys()) {  
  console.log(item);  // 0 1 2
}
// 輸出內容和索引
for (let [item, val] of arr.entries()) {  
  console.log(item + ':' + val); //  0:科大訊飛  1:政法BG  2:前端開發
}

總結:forEach、map、filter、reduce、every、some 都會有 break 和 continue 不生效的問題,由於是在function中,但function解決了閉包陷阱的問題;要使用 break、continue 可使用 for、for...in、for...of、while。 用於遍歷數組元素使用:for(),forEach(),map(),for...of 用於循環對象屬性使用:for...in

相關文章
相關標籤/搜索