JS中遍歷數組經常用到,這里總結了6種遍歷方法,以及各種方法的優劣。
1. for 遍歷數組
1.1 for 的普通遍歷
var name = ['One','Two','Three'];
// for 循環
for(var i = 0; i < name.length; i++) {
console.log(name[i]);
}
1.2 for 優化版遍歷
var name = ['One','Two','Three'];
// 先緩存 name.length
for(var i = 0, len = name.length; i < len; i++) { console.log(name[i]); }
2、while 遍歷數組
ar i = 0;
while (i < name.length) {
console.log(name[i]);
i++;
}
//while 逆向遍歷
var i = name.length;
while (i--) {
console.log(name[i]);
}
3. for...in 方法
數組既可遍歷對象,也可遍歷數組。遍歷數組時也會遍歷非數字鍵名,所以不推薦 for..in 遍歷數組
var a = [1, 2, 3]; for (var key in a) { console.log(a[key]); }
const object = {
name: 'Peter',
age: 12,
isHuman: true
};
for (let key in object) {
console.log(key + '---' + object[key]);
}
4. for...of 方法 (ES6)
var arr = ['a','b','c'];
for(let item of arr) {
console.log(item);
}
5. forEach() 方法
用來遍歷數組中的每一項,不影響原數組,性能差
缺陷 你不能使用break語句中斷循環,也不能使用return語句返回到外層函數。
var arr = [1,2,3,4];
arr.forEach = (function(item) {
console.log(item);
})
const info = [
{id: 1, name: 'zhangsan'},
{id: 2, name: 'lisi'},
{id: 3, name: 'wangwu'}
]
arr.forEach( function(item) {
console.log(item.id + '---' + item.name);
})
6. map() 方法
var arr = [1,2,3,4]; arr.map( function(item) { return item; })
var arr = ['a','b','c'];
var newArray = arr.map(x => x);
浙公網安備 33010602011771號