for-of是在ES6一个新的循环,取代了for-in和forEach()循环。
使用它循环可迭代的对象,Array,Map,Set,String,TypedArray,函数的 arguments 对象NodeList 对象
const iterable = ['a', 'b'];
for (const x of iterable) {
console.log(x);
}
// a b
break或continue在for-of循环内也可以使用:
for (const x of ['a', '', 'b']) {
if (x.length === 0) break;
console.log(x);
}
// a
在循环访问数组时,访问这个元素及其索引(of之前的方括号表示我们正在使用解构):
const arr = ['a', 'b'];
for (const [index, element] of arr.entries()) {
console.log(`${index}. ${element}`);
}
// 0 a 1 b
该of子句的操作数必须是可迭代的。这意味着如果您想要遍历普通对象则需要辅助函数。如果值是类似于数组的,可以通过Array.from()以下方式将其转换为数组:
const arrayLike = { length: 2, 0: 'a', 1: 'b' };
for (const x of arrayLike) { // TypeError
console.log(x);
}
for (const x of Array.from(arrayLike)) { // OK
console.log(x);
}
如果用const声明迭代变量,则将为每次迭代创建新的引用(存储空间)。这可以在下面的代码片段中看到,我们elem通过箭头函数保存当前的引用。之后,您可以看到箭头功能不共享相同的引用elem,它们都有不同的引用。
const arr = [];
for (const elem of [0, 1, 2]) {
arr.push(() => elem);
}
console.log(arr.map(f => f())); // [0, 1, 2]
如果你var声明了迭代变量,那么看看情况是不同的。现在所有的箭头函数都指向相同的引用elem。
const arr = [];
for (var elem of [0, 1, 2]) {
arr.push(() => elem);
}
console.log(arr.map(f => f())); // [2, 2, 2]
我们只看到for-of声明一个迭代的变量,迭代变量也可以是现有的变量,对象属性和数组元素。
你可以迭代一个现有的变量:
let x;
for (x of ['a', 'b']) {
console.log(x);
}
你也可以迭代一个对象属性:
const obj = {};
for (obj.prop of ['a', 'b']) {
console.log(obj.prop);
}
你可以迭代一个数组元素:
const arr = [];
for (arr[0] of ['a', 'b']) {
console.log(arr[0]);
}