JS给对象部署iterator接口并封装成函数
Iterator是一种接口,为各种不同的数据结构提供统一的访问机制。
什么意思呢,你想用for …of遍历你的数据结构, 就得部署Iterator接口。
原生提供这个接口的数据结构有。数组、类数组对象(如argument)、Map和Set结构。
let arr = [1,2,3]
let x = arr[Symbol.iterator]()
x.next() //{ value: 1, done: false }
x.next() //{ value: 2, done: false }
x.next() //{ value: 3, done: false }
x.next() //{ value: undefined, done: true }
for (let i of arr) {
console.log(i);
//1
//2
//3
}
而对象并没有原生部署,obj[Symbol.iterator] //undefiend,可能是因为对象遍历并没有明确的先后顺序去遍历。
那怎么给对象部署Iterator接口呢 ,其实很简单。 在对象上写一个Symbol.iterator方法,就可以被for…of消费了。
这个方法,要返回一个带有value和done属性的next()方法。
把这个过程封装成函数。
let makeIterator = obj => {
obj['x'] = 11
//给传入的对象添加Symbol类型的属性,值为一个函数
obj[Symbol.iterator] = () => {
let keys = Object.keys(obj) //返回对象所有键的数组
let index = 0 //起始为0
return {
next() {
return index > keys.length - 1 ? //判断是否遍历结束
{
value: undefined,
done: true
} : {
value: obj[keys[index++]],
done: false
}
}
}
}
}
let obj = {
a: 'a',
b: 'b',
c: 'c'
}
console.log(obj); //{a: 'a', b: 'b', c: 'c'}
makeIterator(obj)
console.log(obj); //{a: 'a', b: 'b', c: 'c', x: 11, Symbol(Symbol.iterator): ƒ}
let y = obj[Symbol.iterator]()
console.log(y.next()); //{ value: 'a', done: false }
console.log(y.next()); //{ value: 'b', done: false }
console.log(y.next()); //{ value: 'c', done: false }
console.log(y.next()); //{ value: undefined, done: true }
for (let i of obj) {
console.log(i);
//a
//b
//c
}
和原生输出一致了。也可以按需求自行修改
————————————————
版权声明:本文为CSDN博主「赫奇。」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44739881/article/details/102214647