js数组遍历,基本就是for, for in,foreach,for of,map等
let arr = [1, 2, 3, 4, 5];
1. 普通for循环
for(j = 0; j < arr.length; j++){
}
2. 优化版for循环
for(j = 0,len=arr.length; j < len; j++) {
}
3. foreach循环
arr.forEach((num, index) => {
return arr[index] = num * 2;// arr = [2, 4, 6, 8, 10]
});
4. map 遍历
let doubled = arr.map(num => {
return num * 2;// doubled = [2, 4, 6, 8, 10]
});
forEach和map的区别:forEach()方法不会返回执行结果,而是undefined。也就是说,forEach()会修改原来的数组。而map()方法会得到一个新的数组并返回。
5. for in循环
//for-in会遍历到数组的属性
arrTmp.name= "myTest" ;
for ( var i in arrTmp){
console.log(i+ ":" +arrTmp[i])
}
//输出 0:value1 1:value2 2:value3 name:myTest
- 遍历对象中的属性,forin效率是最低的。
- 遍历出来的值是
key。 - 不可以遍历
map/set。 - 可以遍历数组。
6. for of循环
// for-of遍历字符串
let iterable = "china中国" ;
for ( let value of iterable) {
console.log(value);
}
//输出 "c" "h" "i" "n" "a" "中" "国"
ES6中,新增了for-of遍历方法。它被设计用来遍历各种类数组集合,例如DOM NodeList对象、Map和Set对象,甚至字符串也行。官方的说法是:
for...of语句在可迭代对象(包括 Array, Map, Set, String, TypedArray,arguments 对象等等)上创建一个迭代循环,对每个不同属性的属性值,调用一个自定义的有执行语句的迭代挂钩