简体   繁体   English

在JavaScript中通过Generator创建数组

[英]Create Array from Generator in JavaScript

I want to create an array from the values of an generator in JavaScript. 我想从 JavaScript中生成器的值创建一个数组 The generator creates a sequence of dynamic length like this 生成器会像这样创建一个动态长度序列

function* sequenceGenerator(minVal, maxVal) {
    let currVal = minVal;

    while(currVal < maxVal)
        yield currVal++;
}

I want to store those values in an array but using next() until the generator is done does not seem to be the best way possible (and looks quite ugly to be honest). 我想将这些值存储在数组中,但是直到生成器完成后才使用next()似乎并不是最好的方法(老实说看起来很丑)。

var it, curr, arr;

it = sequenceGenerator(100, 1000);
curr = it.next();
arr = [];

while(! curr.done){
    arr.push(curr.value);
}

Can I somehow create an array directly from/within the generator? 我能以某种方式直接在生成器中/内部创建数组吗? If not, can I somehow avoid/hide the loop? 如果没有,我可以以某种方式避免/隐藏循环吗? Maybe by using map or something like that? 也许通过使用map或类似的东西?

Thanks in advance. 提前致谢。

One short solution might be: 一个简短的解决方案可能是:

let list = [...sequenceGenerator(min, max)]

Documentation on MDN 有关MDN的文档

I found another way 我找到了另一种方法

var arr = Array.from( sequenceGenerator(min, max) );

works aswell. 也可以。

You can do it like this; 你可以这样做;

 function* sequenceGenerator() { let currVal = this.minVal; while(currVal <= this.maxVal) yield currVal++; } var obj = {minVal: 10, maxVal:20}, arr; obj[Symbol.iterator] = sequenceGenerator; arr = [...obj]; console.log(arr); 

Although you asked a very specific question, I am wondering if you are trying to solve a more general problem, ie keeping generator results around in a convenient manner. 尽管您提出了一个非常具体的问题,但是我想知道您是否要解决一个更一般的问题,即以一种方便的方式保持生成器的结果。 If go, you might try looking at https://github.com/anywhichway/generx . 如果可以,您可以尝试查看https://github.com/anywhichway/generx This will actually let you treat the generator like it is an array, ie access it using array notation after it has run. 实际上,这将使您将生成器视为一个数组,即在生成器运行后使用数组符号对其进行访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM