介绍for-of循环

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]);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值