简体   繁体   English

我可以在对象声明中进行数组解构赋值吗?

[英]Can I do array destructuring assignment inside an object declaration?

I know I can do this:我知道我可以这样做:

const [MIN_SPEED, MAX_SPEED] = [0.4, 4.0];

What I want is:我想要的是:

const SpeedManager = {
  [MIN_SPEED, MAX_SPEED]: [0.4, 4.0]
}

which is equivalent for:这相当于:

const SpeedManager = {
  MIN_SPEED: 0.4,
  MAX_SPEED: 4.0
}

but the syntax was invalid, how can I achieve that?但是语法无效,我该如何实现呢?

It's not possible - anything involving destructuring will necessary assign values to references (either a standalone variable name, or a nested property).这是不可能的 - 任何涉及解构的事情都需要为引用赋值(独立变量名或嵌套属性)。 But here, you don't have a reference, at least not while still inside the object initializer.但是在这里,您没有引用,至少在对象初始值设定项中没有。

I'd stick with the non-destructuring method, though an ugly alternative is:我会坚持使用非解构方法,尽管一个丑陋的选择是:

 const SpeedManager = {}; ([SpeedManager.MIN_SPEED, SpeedManager.MAX_SPEED] = [0.4, 4.0]); console.log(SpeedManager);

As pointed out, it isn't possible, an alternative could be to zip the two arrays and then use Object.fromEntries() to construct the object for you:正如所指出的,这是不可能的,另一种方法是压缩两个数组,然后使用Object.fromEntries()为您构造对象:

 const zip = (arr1, arr2) => arr1.map((e, i) => [e, arr2[i]]); const res = Object.fromEntries( zip(['MIN_SPEED', 'MAX_SPEED'], [0.4, 4.0]) ); console.log(res);

You need a step between for getting values from an array and return an object.从数组获取值和返回对象之间需要一个步骤。

 const convert = ([MIN_SPEED, MAX_SPEED]) => ({ MIN_SPEED, MAX_SPEED }), speedManager = convert([0.4, 4.0]); console.log(speedManager);

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

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