ES6 for...of循环
生活随笔
收集整理的這篇文章主要介紹了
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 blueconsole.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方法,它可以與break、continue和return配合使用。
?
?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 // foo3、foreach的缺陷
?遍歷數組時 無法break或者return false
?
var arr = [3, 5, 7];arr.forEach(function (value) {console.log(value);if (value == 5) {return false;} }); // 結果是: // 3 // 5 // 7?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的ES6 for...of循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Cloud和Dubbo
- 下一篇: 企业建设什么样的网站才能符合用户?