1. 程式人生 > >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
})