# es6 阮一峰 iterator一篇中一个例子的解读

function Obj(value) {
this.value = value;
this.next = null;
}

Obj.prototype[Symbol.iterator] = function() {
var iterator = { next: next };

var current = this;

function next() {
if (current) {
var value = current.value;
current = current.next;
return { done: false, value: value };
} else {
return { done: true };
}
}
return iterator;
}

var one = new Obj(1);
var two = new Obj(2);
var three = new Obj(3);

one.next = two;
two.next = three;

for (var i of one){
console.log(i); // 1, 2, 3
}

'use strict';

function Obj(value) {
this.value = value;
this.next = null;
}

Obj.prototype[Symbol.iterator] = function () {
var iterator = {
next: next,
returnCurrent: returnCurrent
}; // 遍历器对多返个returnCurrent用于获取当前的current变量的值

var current = this;

function next() {
if (current) {
var value = current.value;
current = current.next;
return {
done: false,
value: value
};
} else {
return {
done: true
};
}
}

function returnCurrent() {
return current;
}
return iterator;
}

var one = new Obj(1);
var two = new Obj(2);
var three = new Obj(3);

one.next = two;
two.next = three;

//   for (var i of one){
//     console.log(i); // 1, 2, 3
//   }

let q = one[Symbol.iterator]();
console.log(q.returnCurrent());
console.log(q.next());
console.log(q.next());
console.log(q.returnCurrent());
console.log(q.next());
console.log(q.returnCurrent());
console.log(q.next());

// console.log .........

// Obj {value: 1, next: Obj}
// Object {done: false, value: 1}
// Object {done: false, value: 2}
// Obj {value: 3, next: null}
// Object {done: false, value: 3}
// null
// Object {done: true}


01-28 300
04-15 1153

09-03 8128
08-26 55
04-27 207
09-18 333
03-20 473
05-18 1570
08-29 1840
09-25 100
04-02 120
05-03 71
10-07 1万+
12-30
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客