gpt4 book ai didi

javascript - 了解实现自定义迭代器

转载 作者:搜寻专家 更新时间:2023-11-01 05:04:18 26 4
gpt4 key购买 nike

我正在尝试理解 Ecmascript 6 迭代器并尝试创建一个行为与 native 数组非常相似的数据结构。

for (let i of [1,2,3]) console.log(i);  //Iterate over data set itself

将输出1,2,3

for (let i of [1,2,3].keys()) console.log(i); //Iterate over a custom iterator from a method

将输出0,1,2,和

var a = [1,2,3];
var keys = [...a.keys()];

将按预期包含 [0,1,2]

因此,

console.log([1,2,3].keys().next());

将输出Object {value: 0, done: false}

现在我创建了一种新的数据类型,并试图让它以同样的方式运行。

var myDogs = function(dogs) {
this.dogs = dogs;
this[Symbol.iterator] = () => {
let i = -1;
return {
next() {
i++;
var dog = Object.keys(dogs)[i];
if (!dog) return {done:true};
return {value:{ dog, hungry:dogs[dog] }, done:false};
}
};
};
this.dogsNames = () => {
return {
[Symbol.iterator]() {
let i = -1;
return {
next() {
i++;
var dog = Object.keys(dogs)[i];
if (!dog) return {done:true};
return {value: dog, done:false};
}
};
}
}
}
};

var dogs = new myDogs({ buddy: true, hasso: false });

这按预期工作(自定义迭代器 - thank you ):

var dogHungryMap = [...dogs];
dogHungryMap == [{ dog: 'buddy', hungry: true }, { dog: 'hasso': hungry: false }]

迭代器 dogsNames() 按预期几乎 工作。这没关系:

var names = [...dogs.dogsNames()];
names == ["buddy", "hasso"]

但这不是:

dogs.dogsNames().next()
VM19728:2 Uncaught TypeError: dogs.dogsNames(...).next is not a function(…)

为什么以及如何重现原生数组的行为?

最佳答案

因为 dogsNames() 返回一个以迭代器为键的对象。因此,您可以在 dogsNames 上使用 for...of,但要直接访问 next(),您需要访问在对象上声明的迭代器函数,如下所示:

dogsNames()[Symbol.iterator]().next()

Babel REPL Example

为了完整起见,共享 next() 函数的完整代码:

var myDogs = function(dogs) {
this.dogs = dogs;
let i = -1;
var iter = {
next() {
i++;
var dog = Object.keys(dogs)[i];
if (!dog) return {done:true};
return {value:{ dog, hungry:dogs[dog] }, done:false};
}
}
this[Symbol.iterator] = () => iter;
this.next = iter.next;
};
var dogList = new myDogs({
dog1: "no",
dog2: "yes"
});
for(const x of dogList) console.log(x);
console.log(dogList.next());
console.log(dogList.next());

关于javascript - 了解实现自定义迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789644/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com