js遍歷方法比較
阿新 • • 發佈:2018-12-05
一。最原始的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}`))