Javascript yield from the function nested inside generator

后端 未结 4 946
醉酒成梦
醉酒成梦 2021-01-03 23:55

This code generates an error:

function *giveNumbers() {
    [1, 2, 3].forEach(function(item) {
        yield item;
    })
}

This is probabl

4条回答
  •  醉话见心
    2021-01-04 00:22

    You can also use while and pass arguments as such (Demo)

    function *giveNumbers(array, start) {
        var index = start || 0;
        while(array.length > index + 1) {
            yield array[index++];
        }
        return array[index];
    }
    
    
    var g = giveNumbers([1,2,3], 0);
    
    var finished = false;
    
    while(!finished) {
        var next = g.next();
        console.log(next.value);
        if(next.done) {
            finished = true;
        }
    }
    

提交回复
热议问题