简体   繁体   English

使用数组解构分配调用哪个 function?

[英]Which function is being called using an array destructuring assigment?

 let [x, y] = ["Ele", "Stack"].reduce((a, s) => { ax = s; ay = s; return a; }, { x: {}, y: {}});

The code snippet above throws an error because is trying to make an array destructuring assignment over an object (key:value).上面的代码片段会引发错误,因为它试图对 object(键:值)进行数组解构赋值。

I have a lack of knowledge我缺乏知识

Which function is being called using an array destructuring assignment?使用数组解构赋值调用哪个 function?

I think you are getting that type error because array destructuring implicitly calls Array[Symbol.iterator] , which is undefined since you're actually returning an object, not an array, from reduce() .我认为您遇到了该类型错误,因为数组解构隐式调用Array[Symbol.iterator] ,这是未定义的,因为您实际上是从reduce()返回 object,而不是数组。 The fix is to replace it with Object destructuring修复方法是将其替换为 Object 解构

 let {x, y} = ["Ele", "Stack"].reduce((a, s) => { ax = s; ay = s; return a; }, { x: {}, y: {}}); console.log({ x, y })

The array destructuring works like it's taking the index of the array and put it into the variables you assigned. array解构的工作方式就像它获取数组的索引并将其放入您分配的变量中。

For example, say the array is-例如,假设数组是-

const arr = [1, 2, 3, 4, 5];

Now you want to destructure the array elements into variables.现在您想将数组元素解构为变量。

const [a, b] = arr;

This will put the value off arr[0] into a and arr[1] into b .这会将arr[0]的值放入a并将arr[1]放入b This way you can assign as many as you want.这样,您可以根据需要分配任意数量。

If you want to put two indexes into two variables and rest of the elements into another array you do it by using spreading operator like this-如果要将两个索引放入两个变量中,并将元素的 rest 放入另一个数组中,则可以使用像这样的扩展运算符来做到这一点 -

const [a, b, ...rest] = arr;

Here, a takes the value of arr[0] and b takes the element of arr[1] and rest takes the rest of the elements into rest array.这里, aarr[0]的值, barr[1]的元素, rest将 rest 的元素放入rest数组中。 So the rest array would be-所以rest阵列将是-

[3, 4, 5]

I hope this will help you.我希望这能帮到您。

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

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