See the chapter about iterators on MDN
https://developer.mozilla.org...Generator expression
Then practice by yourself and find a problem.
//下面这个例子 ,想要实现打印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
//注意与下面这种写法的区别
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.
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.