1. 程式人生 > >for...in、for...of、forEach、map的區別

for...in、for...of、forEach、map的區別

for…in

for…in以原始插入順序訪問物件的可列舉屬性,包括從原型繼承而來的可列舉屬性。

let obj = {
    a:123,
    b:"abc"
}
for(let pro in obj){
    console.log(pro+':' + obj[pro])
}
//a:123
//b:abc

for…in用於遍歷陣列時,可以將陣列看作物件,陣列下標看作屬性名。但用for…in遍歷陣列時不一定會按照陣列的索引順序。

let obj = {
    a:123,
    b:"abc"
}
let arr = [123,'abc']
for(let pro in
arr){ console.log(pro+':' + arr[pro]) } //0:123 //1:abc

for…of

for…of語句在可迭代物件(Array,Map,Set,String,TypedArray,arguments 物件等等)上建立一個迭代迴圈,為每個不同屬性的值執行語句。

let arr = [123,'abc']
for(let item of arr){
    console.log(item)
}
//123
//abc

使用for…in迴圈時,獲得的是陣列的下標;使用for…of迴圈時,獲得的是陣列的元素值。
for…of遍歷Map時,可以獲得整個鍵值對物件:

let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]

也可以只獲得鍵值:

let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);

for (let [key] of iterable) {
  console.log(key);
}
//a
//b
//c

或者分別獲得鍵與值:

let iterable = new
Map([["a", 1], ["b", 2], ["c", 3]]); for (let [key,value] of iterable) { console.log(key+':'+value); } //a:1 //b:2 //c:3

forEach

forEach方法對陣列/Map/Set中的每個元素執行一次提供的函式。該函式接受三個引數:

  • 正在處理的當前元素,對於Map元素,代表其值;
  • 正在處理的當前元素的索引,對於Map元素,代表其鍵,對於Set而言,索引與值一樣。
  • forEach()方法正在操作的陣列物件。
let arr = [1,2,3,4]
arr.forEach(function(value,index,currentArr){
    currentArr[index]=value + 1
})
console.log(arr)//[ 2, 3, 4, 5 ]

map

map() 方法建立一個新陣列,其結果是該陣列中的每個元素都呼叫一個提供的函式後返回的結果。該函式接受的三個引數為:

  • 當前元素
  • 當前索引
  • 當前被呼叫的陣列
var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值為[1, 2, 3], numbers的值仍為[1, 4, 9]