JS for ... of

ES6

介绍

ES6 借鉴 C++、Java、C# 和 Python 语言,引入了for…of循环,作为遍历所有数据结构的统一的方法。

一个数据结构只要部署了Symbol.iterator属性,就被视为具有 iterator 接口,就可以用for…of循环遍历它的成员。也就是说,for…of循环内部调用的是数据结构的Symbol.iterator方法。

for…of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、后文的 Generator 对象,以及字符串。

for…of使用

1
2
3
4
5
6
7
8
9
10
11
const arr = [1,2,3,4,5,6];
for(let num of arr){
console.log(num);
}
//打印结果:
1
2
3
4
5
6

等同于forEach

1
2
3
4
5
6
7
8
9
10
11
const arr = [1,2,3,4,5,6];
arr.forEach(v=>{
console.log(v);
})
//打印结果:
1
2
3
4
5
6