What are Iterables?
[Symbol.iterator]:
"next () {}"
,{done:false, value:"value"}
OR
{ done: true };
[Symbol.iterator] = function() {
// for..of works only with the
// iterator object below, asking it for next values
return {
current: 0,
last: 10,
// next() is called on each iteration
// by the for..of loop
next() {
// it should return the value
// as an object {done:.., value :...}
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
};
Example:
Making a simple object iterable:
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
}
};
// now it works!
for (const num of range) {
console.log({num}); // 1, then 2, 3, 4, 5
}
const range = {
from: 1,
to: 5,
}
// won't work!
for (const num of range) {
console.log({num});
}
Example:
// Different way of writing
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
this.current = this.from;
return this;
},
next() {
if (this.current <= this.to) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
for (let num of range) {
alert(num); // 1, then 2, 3, 4, 5
}
Example:
// Different way of writing
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
this.current = this.from;
return this;
},
next() {
if (this.current <= this.to) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
// Read the loop as:
for (let num = range[Symbol.iterator]().next()) {
alert(num); // 1, then 2, 3, 4, 5
}
Calling an iterator explicitly:
let str = "Hello";
// does the same as
// for (let char of str) alert(char);
let iterator = str[Symbol.iterator]();
while (true) {
let result = iterator.next();
if (result.done) break;
else console.log(result.value);
}
Iterables and array-likes:
Array-likes:
const arrayLike = {
0: "Hello",
1: "World",
length: 2
};
Array.from
let arrayLike = {
0: "Hello",
1: "World",
length: 2
};
let arr = Array.from(arrayLike);
alert(arr.pop());