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