Why is ES6 “yield” a reserved word when called in this context?

前端 未结 5 2138
别跟我提以往
别跟我提以往 2020-12-09 09:34

I am using node 4.1.1. When I run this code

\"use strict\";

function *generator() {
  let numbers = [1,2,3,4,5];
  numbers.map(n => yield (n + 1));
}

f         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 10:06

    [1,2,3,4,5].map(function*(v){yield v+1;}).reduce((accumulator, currentValue) => accumulator = [...accumulator].concat([...currentValue]))
    

    explanation...

    [1,2,3,4,5].map(function*(v){yield v+1;})
    

    pack all values into generator resulting

    (5) [Generator, Generator, Generator, Generator, Generator]

    unpack into flat array

    .reduce((accumulator, currentValue) => accumulator = [...accumulator].concat([...currentValue]))
    

    (5) [2, 3, 4, 5, 6]

    for normal use

    [1,2,3,4,5].map(function*(v){yield v+1;}).forEach(v => console.log([...v][0]))
    

    2

    3

    4

    5

    6

    [...v][0] is a bit ugly but it is works.

提交回复
热议问题