[英]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.如果我们同时解构
object
和array
,这也是可能的。
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);
options
array is integer
number.
options
数组的键是integer
编号。
Actually, it's index.
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
数组中解构第一个元素。
options
property from the context
object.context
object 中解构options
属性。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.