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
}

原有代码是这样的,其实相对于one下next连的是two的{value:2,next:{...three}},three的Object是这样的{value:3,next:null}。


那下面的for...of也是怎么执行的呢?其实for...of只会去[symbol.iterator]拿一次遍历器对象iterator(Object),拿到后就会直接执行next()方法,而每次执行完都会把current变量(symbol.iterator,返回的是一个对象,所以current变量会一直存在)重置为下一个next对象直到用完为止(返回{done:true})。

不用for...of其它是下面这样的执行方式:

'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}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页