Javascript中的遍历

ES5 具有遍历数组功能的有 forEach、map、filter、some、every、reduce、reduceRight

foreach:

1
2
3
4
5
6
7
var arr = [1,2,3,4];
let sum=0
arr.forEach(function(value,index,array){
array[index] == value; //结果为true
sum+=value;
});
console.log(sum); //结果为 10

但是使用 foreach 遍历数组的话,使用 break 不能中断循环,使用 return 也不能返回到外层函数。

set 和 map

遍历 map 对象时适合用解构,例如:

1
2
3
for (var [key, value] of phoneBookMap) {
console.log(key + "'s phone number is: " + value);
}

for-in

1
2
3
4
5
6
7
8
Array.prototype.method=function(){
  console.log(this.length);
}
var myArray=[1,2,4,5,6,7]
myArray.name="数组"
for (var index in myArray) {
console.log(myArray[index]);
}
  1. index 索引为字符串型数字,不能直接进行几何运算
  2. 遍历顺序有可能不是按照实际数组的内部顺序
  3. for in 会遍历所有可枚举属性,包括原型。包括上述的 name 和 method

通常用 for in 来遍历对象的键名,如果对象是个数组的话,也会只返回键名

for of

1
2
3
4
5
6
7
8
Array.prototype.method=function(){
  console.log(this.length);
}
var myArray=[1,2,4,5,6,7]
myArray.name="数组";
for (var value of myArray) {
console.log(value);
}

注意:for in 遍历的是数组的索引(即键名),而 for of 遍历的是数组元素值。

总结

  • for..of 适用遍历数/数组对象/字符串/map/set 等拥有迭代器对象的集合.但是不能遍历对象,因为没有迭代器对象.与 forEach()不同的是,它可以正确响应 break、continue 和 return 语句
  • for-of 循环不支持普通对象,但如果你想迭代一个对象的属性,你可以用 for-in 循环(这也是它的本职工作)或内建的 Object.keys()方法:
1
2
3
for (var key of Object.keys(someObject)) {
console.log(key + ": " + someObject[key]);
}

参考 1

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信