【发布时间】:2021-02-03 06:13:26
【问题描述】:
学习在 Javascript 中使对象可迭代。
对象是:
var arrayLikeObject = {
0: "hello",
1: "there",
2: "crappy coder",
length: 3,
}
然后我这样做是为了让它可迭代:
arrayLikeObject[Symbol.iterator] = function(){
return {
current: 0, // <---- but... it IS defined.
next() {
// let current = 0; // putting it here makes it work
if(current < this.length) {
let a = current;
current++;
return {done: false, value: this[a]};
}
else {
return {done: true};
}
}
};
};
然后当我运行它时:
console.log("after making it iterable: ==============");
for(let str of arrayLikeObject) {
console.log(str);
}
我得到“当前未定义”但据我所知,它是。我只是无法理解。我认为函数可以看到它们范围之外的变量,但不能反过来,除非如果这是正确的术语,它们会被“掩盖”。我忘了。
【问题讨论】:
-
current->this.current。 变量和对象属性在JS中是不同的。 -
明白了。有点忘记了在创建对象文字时需要在对象方法中使用它,以便在其方法中使用对象属性:-o。有没有其他地方可以解决这样的问题,有人在精神上受阻时需要帮助(在谷歌搜索、检查教程和 stackoverflow 答案之后,仍然无法“解开”)。比如,第二双眼睛?猜测这类问题很快就会被否决 x)
-
其实。刚刚注意到(因为一堆其他打印输出妨碍了它。它仍然不起作用,我不再使用
if(this.current < this.length)得到任何错误,但我也没有从 for...of 循环中得到任何结果。
标签: javascript iterable