ES6 for...of循環


1、for of

const arr = ['red', 'green', 'blue']; for(let v of arr) { console.log(v); // red green blue
}

for...of循環可以代替數組實例的forEach方法。

const arr = ['red', 'green', 'blue']; arr.forEach(function (element, index) { console.log(element); // red green blue
  console.log(index);   // 0 1 2
});

JavaScript 原有的for...in循環,只能獲得對象的鍵名,不能直接獲取鍵值。ES6 提供for...of循環,允許遍歷獲得鍵值。

var arr = ['a', 'b', 'c', 'd']; for (let a in arr) { console.log(a); // 0 1 2 3
} for (let a of arr) { console.log(a); // a b c d
}

上面代碼表明,for...in循環讀取鍵名,for...of循環讀取鍵值。如果要通過for...of循環,獲取數組的索引,可以借助數組實例的entries方法和keys方法.

for of:不同於forEach方法,它可以與breakcontinuereturn配合使用

 

 2、for in的缺陷

for in會遍歷出原型對象以及對象本身屬性值。

Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; var arr = [3, 5, 7]; arr.foo = 'hello'; for (var i in arr) { console.log(i); } // 結果是: // 0 // 1 // 2 // foo // arrCustom // objCustom
Object.prototype.objCustom = function() {}; Array.prototype.arrCustom = function() {}; var arr = [3, 5, 7]; arr.foo = 'hello'; for (var i in arr) { if (arr.hasOwnProperty(i)) { console.log(i); } } // 結果是: // 0 // 1 // 2 // foo

3、foreach的缺陷

 遍歷數組時 無法break或者return false

 

var arr = [3, 5, 7]; arr.forEach(function (value) { console.log(value); if (value == 5) { return false; } }); // 結果是: // 3 // 5 // 7

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM