數組
遍歷
普通遍歷
最簡單的一種,也是使用頻率最高的一種。
let arr = ['a', 'b', 'c', 'd', 'e'] for (let i = 0; i < arr.length; i++) { console.log(i, ' => ', arr[i]) }
優化: 緩存數組長度:
let arr = ['a', 'b', 'c', 'd', 'e'] for (let i = 0, len = arr.length; i < len; i++) { console.log(i, ' => ', arr[i]) }
使用臨時變量,將長度緩存起來,避免重復獲取數組長度,當數組較大時優化效果才會比較明顯。
for-in
這個循環很多人愛用,但實際上,經分析測試,在眾多的循環遍歷方式中它的效率是最低的。
let arr = ['a', 'b', 'c', 'd', 'e'] for (let i in arr) { console.log(i, ' => ', arr[i]) }
for-of
這種方式是es6里面用到的,性能要好於forin,但仍然比不上普通for循環。
let arr = ['a', 'b', 'c', 'd', 'e'] let index = 0 for (let item of arr) { console.log(index++, ' => ', item) }
forEach
數組自帶的foreach循環,使用頻率較高,實際上性能比普通for循環弱。
let arr = ['a', 'b', 'c', 'd', 'e'] arr.forEach((v, k) => { console.log(k, ' => ', v) })
forEach接受第三個參數,指向原數組,沒有返回值,對其進行操作會改變原數組對象
let ary = [12, 23, 24, 42, 1] let res = ary.forEach((item, index, input) => { input[index] = item * 10 }) console.log(res) //-->undefined console.log(ary) //-->會對原來的數組產生改變
