Iterables
iterable 就是 array 的大眾化,讓物件可以使用 for...of 迴圈。
Symbol.iterator
自己創造一個可以迴圈的物件。
let range = {
from: 1,
to: 5
};
// We want the for..of to work:
// for(let num of range) ... num=1,2,3,4,5
// 創造可迴圈物件
let range = {
from: 1,
to: 5
};
// 1. call to for..of initially calls this
range[Symbol.iterator] = function() {
// ...it returns the iterator object:
// 2. Onward, for..of works only with this iterator, asking it for next values
return {
current: this.from,
last: this.to,
// 3. next() is called on each iteration by the for..of loop
next() {
// 4. 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 };
}
}
};
};
// now it works!
for (let num of range) {
alert(num); // 1, then 2, 3, 4, 5
}
// 執行了 2 個 for..of
let 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
}String is iterable
Calling an iterator explicitly
Iterables and array-likes
iterables 是有 Symbol.iterator 方法的物件
array-like 是有 index 跟 length 的物件
Array.from
Array.from() 可以將 iterable / array-like 帶入返回新的 array。
Last updated
Was this helpful?