背景
javascript中的for循環選擇多種多樣,可你知道其中的差別在哪里嗎?什么時候又該用哪種循環才是最佳策略?以上這些是本文想討論的,歡迎交流。
說明
1、20年前的for循環
//20年前的寫法
let len = myArray.Length for (let index = 0; index < len; index++) { console.log(myArray[index]) }
- 中規中矩。
2、forEach
//ES5的寫法 myArray.forEach(function(index){ //操作你的index,index即為數組中的元素 })
- 缺點,沒有返回值。
3、for...in
//ES5的寫法,勸你慎重 for (let index in myArray) { // 千萬別這樣做 console.log(myArray[index]); }
- 最糟糕的做法,因為此時的index是字符串,而且不一定按照數組的順序輸出,很嚇人。
- 僅適用於遍歷普通對象的key。
4、for...of
/**ES6寫法 *支持數組 *類數組對象(如:NodeList對象) *字符串 *Map *set */ for (let value of myArray) { console.log(value); }
- 各種優秀啦