简体   繁体   English

从数组的第一个索引的 object 解构值

[英]Destructuring values from object of the first index of array

How can I replace accessing the temp variable values from the following code extract?如何替换从以下代码提取中访问临时变量值? I have tried to get all values through the default JS code, however, I would like to use destructuring here我试图通过默认的 JS 代码获取所有值,但是,我想在这里使用解构

const temp = context.options[0]; // <----- here
const avoidPattern = [
    'foo', 'bar', 'abc', 'value', 'temp', 'num'
];


return [...avoidPattern, ...temp]

You might use this你可以用这个

 const context = { options: [1,2,3] } const [temp] = context.options; console.log(temp)

This can also be possible if we destructure object and array at the same time.如果我们同时解构objectarray ,这也是可能的。

 const context = { options: [1, 2, 3] }; const { options: [temp] } = context; console.log(temp);

 let arr=['data','title','image']; let [first]=arr[1]; console.log(first);

An interesting that Array in JavaScript is an object, So you can destructure an array as object like this JavaScript 中的一个有趣的数组是 object,因此您可以像这样将数组解构为 object

 const context = { options: [1, 2, 3] }; const { options } = context; // [1, 2, 3] const {0:firstItem } = options; console.log(firstItem);
As you can see, key of options array is integer number. 如您所见, options数组的键是integer编号。 Actually, it's index. 其实就是索引。 In this way, you can destructure an array with the long array by index in the that way. 通过这种方式,您可以通过这种方式通过索引来解构具有长数组的数组。

More details here: Object destructuring solution for long arrays?更多细节在这里: Object 解构解决方案长 arrays?

If you want to destructure the first element out of the options array.如果要从options数组中解构第一个元素。

  1. You can first destructure the options property from the context object.您可以首先从context object 中解构options属性。
  2. Then you can destructure the first item from the options array.然后,您可以解构options数组中的第一项。

 const context = { options: [1, 2, 3] }; // Destucture the options key property const {options} = context console.log(options) // [1,2,3] // Next, destructure the first item from the array const [first] = options console.log(first) // 1

You can also combine the two steps mentioned above using the colon : operator, which is used to provide an alias while destructing an object.您还可以使用冒号:运算符组合上述两个步骤,该运算符用于在破坏 object 时提供别名。

 const context = { options: [1, 2, 3] }; // Destucture the options property // and in the alias destructure the first item of the array const {options: [first]} = context console.log(first) // 1

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

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