《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