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号