JavaScript中各种遍历方法的总结

JavaScript中各种遍历方法的总结

for

最基础的循环

for…in

可以用来遍历对象

var o ={
     name:"jack",
     age:20,
     city:"beijing"
};
for (var key in o){
      alert(key)  //"name","age","city"
}

for…of

可以遍历所有拥有iterator遍历器的数据结构。包括set和map。

var a = ["A","B","C"];
var s = new Set(["A","B","C"]);
var m = new Map([[1,"x"],[2,"y"],[3,"z"]]);
for (var x of a){
     alert(x);
}
for (var x of s){
     alert(x);
}
for (var x of m){
     alert(x[0]+"="+x[1]);
}

forEach

接受一个函数作为参数,这个函数有三个参数:
当前元素、当前索引、操作的数组对象。
无法使用break中断或者用return返回到外层函数。

let arr = [1,2,3,4]
arr.forEach(function(value,index,currentArr){
    currentArr[index]=value + 1
})
console.log(arr)//[ 2, 3, 4, 5 ]

map

接受一个函数作为参数,创建一个新数组,该数组中每个元素都调用这个函数后返回的结果。
函数接收的三个参数:
当前元素、当前索引、当前被调用数组

arr.map(function(m,n,k){
console.log(m); //val
console.log(n); //index
console.log(n); //arr
})