学习在 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);
}
我得到“当前未定义”但据我所知,它是。我就是不明白。我认为函数可以看到其作用域之外的变量,但反过来却不行,除非如果这是正确的术语,它们会被“掩盖”。我忘了。
胡说叔叔
相关分类