ES6 iterable 新类型
iterable
为统一集合类型,ES6标准引入了新的 iterable 类型,Array,Map,Set 都属于iterable类型
iterable 类型的集合可以通过新的 for...of 循环方法来遍历。
for...of 用法
var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for(var x of a){ // 遍历Array
console.log(x);
}
for(var x of s){ // 遍历Set
console.log(x);
}
for(var x of m){ // 遍历Map
console.log(x[0] + '=' + x[1]);
}
for...of 循环和 for...in循环的区别在于,手动为 Array 对象添加额外属性后,for...in循环会将额外添加的属性也循环出来。
var a = ['A', 'B', 'C'];
a.name = 'Hello';
for(var x in a){
console.log(x); // '0', '1', '2', 'name'
}
for...of 修复了以上问题,只喜欢元素本身
var a = ['A', 'B', 'C'];
a.name = 'Hello';
for(var x of a){
console.log(x); // 'A', 'B', 'C'
}
forEach
forEach 方法,接收一个函数,每次迭代都会自动回调该函数
参数讲解
var a = ['A', 'B', 'C'];
a.forEach(function (element, index, array){
// element 指向当前元素的值
// index 指向当前索引
// array 指向Array对象本身
})
forEach 方法遍历 Array,Set, Map 对象讲解
Array
var a = ['A', 'B', 'C'];
a.forEach(function (element){
console.log(element);
});
Set
var s = new Set(['A', 'B', 'C']);
s.forEach(function(element, sameElement, set){
console.log(element);
});
Map
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
m.forEach(function (value, key, map){
console.log(value);
});
文献来源(https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/00143450082788640f82a480be8481a8ce8272951a40970000)

浙公网安备 33010602011771号