生成函数中的yield statment行为

时间:2017-09-21 17:15:08

标签: javascript ecmascript-6 iterator generator yield

了解生成器我已经得到了example from MDN

function* fibonacci() {
  var fn1 = 0;
  var fn2 = 1;
  while (true) {  
    var current = fn1;
    fn1 = fn2;
    fn2 = current + fn1;
    var reset = yield current;
    if (reset) {
        fn1 = 0;
        fn2 = 1;
    }
  }
}

var sequence = fibonacci();
console.log(sequence.next().value);     // 0
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 2
console.log(sequence.next().value);     // 3
console.log(sequence.next().value);     // 5
console.log(sequence.next().value);     // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 2

我很欣赏一个精心制作的文字,一起回答以下问题:
reset分配给yield current后,为什么yield会对其进行测试? 这导致了一个更普遍的问题: next()在作业中的表现如何? 传递给function *createIterator() { let first = yield 1; let second = yield first + 2; // 4 + 2 yield second + 3; // 5 + 3 } let iterator = createIterator(); console.log(iterator.next()); // "{ value: 1, done: false }" console.log(iterator.next(4)); // "{ value: 6, done: false }" console.log(iterator.next(5)); // "{ value: 8, done: false }" console.log(iterator.next()); // "{ value: undefined, done: true }" 的值究竟在哪里? 因为这里的代码

yield first + 2

现在我将yield (first + 2)替换为class Class1(webapp.RequestHandler): def get(self): random_id = str(uuid.uuid1()) time_now = int(time.time()) info = { id: random_id, now: time_now } json_info = json.dumps(info) print json_info self.response.write(info) class Class2(webapp.RequestHandler): def get(self): getting_info = self.Class1() getting_info_time = getting_info['now'] print getting_info_time ,但结果仍然相同。那背后的机制是什么?

由于我是这种编程风格的新手,所以一步一步的详细解答将是金色的。 我再说一下速度读者:请帮助我理解Javascipt如何通过指令执行这样的代码指令,谢谢

1 个答案:

答案 0 :(得分:0)

分配yields时,它有两种用途:

首先是它的主要用途:

它确定迭代器的next()方法返回的每个对象。

第二个是分配时:

要理解的最棘手的部分是屈服的主要作用首先在这里执行(作业的右边部分)。然后生成器代码冻结。下次调用next()时,它将恢复执行。首先将当前 next()参数分配给作业的左侧部分。

知道那个和那个:

  

每次调用生成器的next()方法时,生成器   恢复执行并运行,直到达到以下之一:

     

产量,导致发电机再次暂停并返回发电机的新值。下次调用next()时,   在yield之后立即执行恢复语句。   ...

这是第二个例子的执行情况:

iterator.next()--->>>
yields 1
//next returns 1 in the 'value' property
//Freezing until the next call to next
iterator.next(4)--->>>
let first =4
yield first + 2;
//next returns 6 in the 'value' property
//Freezing until the next call to next 
iterator.next(5)--->>>
let second = 5
yield second + 3;
// That is 8 in the value property

有用的链接: