天天看點

js周遊方法比較

一。最原始的for循環
let myArray = ['a','b','c'];
for(var index = 0; index < myArray.length; index++) {
    console.log(index,myArray[index]);
}  
// 0 "a"
// 1 "b"
// 2 "c"
           
二。forEach

上面寫法較為麻煩,是以數組提供了forEach方法。

myArray.forEach(function (value) {
        console.log(value);
    });
//a
//b
//c
           

該方法存在一個問題,即不能中途跳出循環。break,return,continue都不能奏效。

三。for…in
for (var index in myArray) {
  console.log(index,myArray[index]);
}
// 0 a
// 1 b
// 2 c
           

for...in

缺點:

for...in

周遊數組的鍵名,數組的鍵名是數字,其不僅周遊數字鍵名,還會周遊手動添加的其他鍵,甚至包括原型鍊上的鍵。

for...in

循環主要是為對象的周遊設計的,不适用于數組的周遊。

#####四。map

arr.map(function () {
});
           
五。for…of
for (let value of myArray) {
  console.log(index,value);
}
//a
//b
//c
           

for...of

沒有

for...in

forEach

的缺點,它可以與

break

continue

return

配合使用。

for...of

不能用于周遊普通的對象,會報錯

let obj = {
  edition: 6,
  committee: "TC39",
  standard: "ECMA-262"
};

for (let e in obj) {
  console.log(e);
}
// edition
// committee
// standard  for...in可以周遊對象鍵名

for (let e of es6) {
  console.log(e);
}
// TypeError: es6[Symbol.iterator] is not a function
           

解決方案:

(1)使用Object.keys()方法将對象的鍵名生成一個數組,然後周遊這個數組。

for(var key of Object.keys(obj)) {
    console.log(key + ': ' + obj[key])
}
//edition: 6
//committee: TC39
//standard: ECMA-262
           

(2) 使用 Generator 函數将對象重新包裝一下。

function* entries(obj) {
  for (let key of Object.keys(obj)) {
    yield [key, obj[key]];
  }
}

for (let [key, value] of entries(obj)) {
  console.log(key, '->', value);
}
// a -> 1
// b -> 2
// c -> 3
           

(3)利用Object.entries()與解構指派

Object.entries(obj).forEach(([key,value]) => console.log(`${key}:${value}`))
           

繼續閱讀