How to get the nth value of a JavaScript generator?

前端 未结 4 1438
萌比男神i
萌比男神i 2020-12-19 18:07

How can I get the nth value of a generator?

function *index() {
  let x = 0;
  while(true)
    yield x++;
}

// the 1st value
let a = index();
console.log(a.         


        
4条回答
  •  暖寄归人
    2020-12-19 18:21

    A simple loop will do:

    let n = 10,
        iter = index();
    while (--n > 0) iter.next();
    console.log(iter.next().value); // 9
    

提交回复
热议问题