hanyujianke 2019-11-12
什么是 Iterator 接口
JS表示集合的对象主要有Array、Set、Object、Map,在以前,遍历它们需要使用2种不同的方法,而现在,JS提出了Iterator机制,可以给不同的数据结构提供统一的遍历方法,就是for…of。换句话说,只有部署了Iterator的数据才能用for…of遍历。
Iterator的遍历过程是这样的:
next方法,可以将指针指向数据结构的第一个成员。next方法,指针就指向数据结构的第二个成员。next方法,直到它指向数据结构的结束位置。每一次调用next方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含value和done两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。
{
let arr = [‘hello‘, ‘world‘]
let map = arr[Symbol.iterator]()
console.log(map.next()) // {value: "hello", done: false}
console.log(map.next()) // {value: "world", done: false}
console.log(map.next()) // {value: undefined, done: true}
}{
// 自定义 Object iterator 接口
let obj = {
start: [1, 2, 3],
end: [4, 5, 6],
[Symbol.iterator](){
let that = this
let index = 0
let arr = that.start.concat(that.end) // 数组合并
let len = arr.length
return {
next () {
// 遍历过程
if (index < len) {
return {
value: arr[index++],
done: false // 继续循环
}
} else {
return {
value: arr[index++],
done: true // 终止循环
}
}
}
}
}
}
// for of 验证是都能循环了
for (let key of obj) {
console.log(key) // 1 2 3 4 5 6
}
}
没自定义 iterator 接口 Object 使用 for of 循环是会报错的
{
let obj = {
start: [1, 2, 3],
end: [4, 5, 6],
}
for (let value of obj) {
console.log(value) // TypeError: obj is not iterable
}
}
调用 Iterator 接口的场合
解构赋值
{
let set = new Set().add(‘a‘).add(‘b‘).add(‘c‘);
let [x,y] = set;
console.log(set) // Set(3) {"a", "b", "c"}
console.log(x) // a
console.log(y) // b
let [first, ...rest] = set;
console.log(first) // a
console.log(rest) // [‘b‘,‘c‘]
}
扩展运算符
{
// 例一
var str = ‘hello‘;
console.log([...str]) // [‘h‘,‘e‘,‘l‘,‘l‘,‘o‘]
// 例二
let arr = [‘b‘, ‘c‘];
console.log([‘a‘, ...arr, ‘d‘]) // [‘a‘, ‘b‘, ‘c‘, ‘d‘]
}