JavaScript iterator Problem with iterator?
ringa_lee
ringa_lee 2017-05-19 10:47:40
0
2
736

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.

ringa_lee
ringa_lee

ringa_lee

reply all(2)
黄舟

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.

phpcn_u1582

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次
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template