for of

84 阅读1分钟

for...of循环可以代替数组实例的forEach方法。 而且比forEach更好

forEach遍历途中无法停止 即使用return,break无效 for...of没有这个缺点

const arr = ['red', 'green', 'blue'];
 
arr.forEach(function (element, index) {
  console.log(element); // red green blue
});
 
for (let a of arr) {
  console.log(a); //  red green blue
}

对于普通的对象,for...of结构不能直接使用,会报错,必须部署了 Iterator 接口后才能使用