从ES6生成器创建一个数组 [英] Creating an array from ES6 generator

查看:469
本文介绍了从ES6生成器创建一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  function * gen(){for(let i = 0; i< 3; i ++){yield i; }} let [... b] = gen(); console.log(b); // [0,1,2]  



$ c> b 将分配 [0,1,2] 。为什么这个工作?

解决方案

我想我在这篇文章。这里的 ... 操作符是其余的操作符。当用于重组数组时,它会将被破坏的数组的所有未分配元素分配给另一个数组。必须在收到结构化值的变量列表中的最后一个项目上使用其余操作符。例如:



  let a = [1,2,3,4, 5]; let [first,second,... remaining] = a; console.log(first); // 1console.log(second); // 2console.log(remaining); // [3,4,5]  



因为 b 是唯一被破坏并使用其余操作符的整个数组。



ES6似乎运行生成器,并将结果转换为 = 右侧的数组。


Let's say I want to assign the result of an ES6 generator to an array variable.

function* gen() {
   for(let i = 0; i < 3; i++) {
       yield i;
   }
}

let [...b] = gen();
console.log(b); // [0, 1, 2]

Here b will be assigned [0, 1, 2]. Why does this work?

解决方案

Well I think I found the answer on this post. The ... operator here is the rest operator. When used to destructure an array, it will assign all unassigned elements of the array being destructured to another array. The rest operator must be used on the last item in the list of variables receiving the destructured values. For example:

let a = [1, 2, 3, 4, 5];
let [first, second, ...remainder] = a;

console.log(first); // 1
console.log(second); // 2
console.log(remainder); // [3, 4, 5]

In the question, since b is the only thing being destructured and its using the rest operator, the entire array is assigned to it.

ES6 appears to run the generator and turn the result into an array on the right hand side of the =.

这篇关于从ES6生成器创建一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆