JavaScript 數組遍歷

原文連接

《JavaScript 數組遍歷》javascript

參考

For-each over an array in JavaScript?
Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?
forEach and runtime costhtml


開始遍歷

多種選擇:java

  • for數組

  • for-in瀏覽器

  • forEach 以及相關的(ES5+)ide

  • for-of(ES6+)oop

  • 使用迭代器(ES6+)
    <!-- more -->code

先聲明並初始化一個數組吧:let a = ["a", "b", "c"];htm

使用 for 循環

for (let i = a.length; i--; ) {
    console.log(a[i]);
}

使用 for-in (不推薦)

for (let i in a) {
    console.log(a[i]);
}

forEach 以及相關的

a.forEach((e, i, a) => console.log(`element:${e}, index:${i}, array:${a}`));
a.map(n => console.log(n));

使用 for-of

for (let val of a) {
    console.log(val);
}

使用迭代器

for (let entry, itr = a[Symbol.iterator](); !(entry = itr.next()).done; ) {
    console.log(entry.value);
}

比較上述遍歷方式

  • for 這是最多見的遍歷方式,瀏覽器都支持blog

  • for-in 不推薦,兩個緣由:不能保證遍歷的順序是預期的;遍歷可能會帶出原型鏈上的屬性

  • forEach() 很是好用的遍歷方式,ES5+,若是擔憂運行時資源消耗的問題,能夠看看 forEach and runtime cost。缺陷是不能使用 break,但能夠用 try-catch 來 hack

  • map() ES5+,適用於「鏈式」場景,如 a.map(i => i + i).sort();

  • for-of ES6+,適用於所有元素的遍歷,缺陷是不知道 index

  • 迭代器,ES6 新特性,你們能夠慢慢玩


EOF

相關文章
相關標籤/搜索