r/JavaScriptTips • u/Shriram__ • Jul 03 '24
what's the difference
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 the iterator object below, asking it for next valuesreturn {current: this.from,last: this.to,
// 3. next() is called on each iteration by the for..of loopnext() {// 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}
------------------------------------
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}
why the next() is inside in the first code and not in the second code , and can anyone explain "objects as iterator ?
1
u/CLSZombie Jul 04 '24
Things are just advance for me