I'm learning to make objects iterable in Javascript.
My object is:
var arrayLikeObject = {
0: "hello",
1: "there",
2: "crappy coder",
length: 3,
}
then I do this to make it iterable:
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};
}
}
};
};
then when I run it with:
console.log("after making it iterable: ==============");
for(let str of arrayLikeObject) {
console.log(str);
}
I get "current is not defined". But as far as I can see, it is defined. I don't understand. I thought functions could see variables outside their scope, but not the other way around, unless they get "overshadowed".
current->this.current. A variable and an object property are different in JS.if(this.current < this.length)anymore, but I get no results from the for...of loop either.