遍历器的yield和return

不同点1

function* helloWorldGenerator() {
    yield 1;
    yield 2;
}

var hw = helloWorldGenerator();
hw.next();
// { value: '1', done: false }

hw.next();
// { value: '2', done: false }

hw.next();
// { value: 'undefined', done: true }
function* helloWorldGenerator() {
    yield 1;
    return 2;
}

var hw = helloWorldGenerator();
hw.next();
// { value: '1', done: false }

hw.next();
// { value: '2', done: true }

hw.next();
// { value: 'undefined', done: true }

用yield,第二次执行next时,返回对象的done属性是false,而用return,第二次执行next时,返回对象的done属性值是true。

这是什么原因呢?搜索了下资料,原来yield代表遍历器函数暂停执行,并未结束,yield以下的内容还会在再次调用next方法后继续执行(尽管最后一个yield后面没有代码了),因而done的值是false;

而return代表程序终止,遍历器后面的内容不会再执行,因而done是true;

不同点2

function* genFuncWithReturn() {
    yield 'a';
    yield 'b';
    return 'c';
}

var genObj = genFuncWithReturn();
for( var i of genObj){
    console.log(i);
}
// a b

for of 会忽略return的返回值,而只遍历yield的返回值。

posted @ 2016-04-28 18:56  静水渊  阅读(344)  评论(0)    收藏  举报