javascript - 如何获取 JavaScript 生成器的第 n 个值?

标签 javascript generator ecmascript-6

如何获取生成器的第 n 个值?

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

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

// the 3rd value
let b = index();
b.next();
b.next();
console.log(b.next().value); // 2

// the nth value?
let c = index();
let n = 10;
console.log(...); // 9

最佳答案

你可以定义一个像in python这样的枚举方法:

function *enumerate(it, start) {
   start = start || 0;
   for(let x of it)
     yield [start++, x];
}

然后:

for(let [n, x] of enumerate(index()))
  if(n == 6) {
    console.log(x);
    break;
  }

http://www.es6fiddle.net/ia0rkxut/

沿着同样的思路,也可以重新实现 pythonic rangeislice:

function *range(start, stop, step) {
  while(start < stop) {
    yield start;
    start += step;
  }
}

function *islice(it, start, stop, step) {
  let r = range(start || 0, stop || Number.MAX_SAFE_INTEGER, step || 1);
  let i = r.next().value;
  for(var [n, x] of enumerate(it)) {
    if(n === i) {
      yield x;
      i = r.next().value;
    }
  }
}

然后:

console.log(islice(index(), 6, 7).next().value);

http://www.es6fiddle.net/ia0s6amd/

现实世界的实现需要更多的工作,但您明白了。

关于javascript - 如何获取 JavaScript 生成器的第 n 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410359/

相关文章:

javascript - Laravel 5.2 - 使用 jquery 自动完成下拉菜单

javascript - 使用 onclick 获取值

python - 非常大范围的高效随机生成器(在 python 中)

javascript - 通过 React 的 useState Hook 设置状态时,删除键的最佳或最有效的方法是什么?

javascript - Angular JS : binding in ng-show not working

javascript - Ext js 编码标准/最佳实践

php - 将 "yield from"与迭代器或生成器一起使用时的行为差异

python - 在 Python 中重置生成器对象

javascript - 迁移到react-router v4 - 需要 router props 的子路由

javascript - React 应用程序中的 Vega-tooltip