See the chapter about iterators on MDN
https://developer.mozilla.org...Generator expression
Then practice by yourself and find a problem.
//下面這個例子 ,想要實現(xiàn)打印3,4,5
var add=function(x,y){
var current=x;
return {
[Symbol.iterator]:function(){return this;},
next:function(){ return current++;}
}
}
var it=add(3,5);
console.log(it.next());
console.log(it.next());
console.log(it.next());
//結果 3 4 5
//注意與下面這種寫法的區(qū)別
console.log(add(3,5).next()); //3
console.log(add(3,5).next()); //3
console.log(add(3,5).next()); //3
The code is relatively simple. What I want to ask is why in the second method, when I do not assign the add() method to it, I cannot generate iterations. According to my understanding, add(3,5) in this example is equivalent to it, but the result is obviously not the case.
ringa_lee
The traversal process of Iterator is like this.
(1) Create a pointer object pointing to the starting position of the current data structure. In other words, the traverser object is essentially a pointer object.
(2) The first time you call the next method of the pointer object, you can point the pointer to the first member of the data structure.
(3) When the next method of the pointer object is called for the second time, the pointer points to the second member of the data structure.
(4) Keep calling the next method of the pointer object until it points to the end of the data structure.
Every time you execute add you will get an object. Each of these objects has an independent current. So it = add()
和多次 add()
once is not equivalent.
var it=add(3,5); // 對象1
console.log(it.next()); // 對象1 第1次
console.log(it.next());
console.log(it.next()); // 對象1 第3次
console.log(add(3,5).next()); // 對象2 第1次
console.log(add(3,5).next()); // 對象3 第1次