This works fine for me:
const iterable = [1, 2, 3];
for (const value of iterable) {
console.log(value);
}
However this does not work:
const iterable = {1:10, 2:20, 3:30};
for (const value of iterable) {
console.log(value);
console.log(iterable[value]);
}
Instead giving me the error:
Uncaught TypeError: iterable[Symbol.iterator] is not a function(…)
How should I be doing this?
This is what I do now:
for(const value in iterable){
if (iterable.hasOwnProperty(value)) {
console.log(value);
console.log(iterable[value]);
}
}
for..of only works for iterable objects. You could implement an iterator like this:
const iterable = {
[Symbol.iterator]() {
return {
i: 1,
next() {
if (this.i <= 3) {
return { value: 10 * this.i++, done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (const value of iterable2) {
console.log(value);
} // 10, 20, 30
To iterate over plain objects, other than for...in which I think is fine, you could use Object.keys:
const iterable = {1:10, 2:20, 3:30};
Object.keys( iterable ).forEach( key => {
console.log( iterable[key] );
}); // 10, 20, 30
BTW your first example throws a syntax error, maybe you meant const iterable = [1,2,3]? Then it would work since Arrays are iterable objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With