Cod*_*gue 17 javascript destructuring ecmascript-7 ecmascript-next
我有一系列的值,如:
const arr = [1,2,3];
Run Code Online (Sandbox Code Playgroud)
有什么方法可以使用解构来创建以下输出?如果没有,我在ES6(或更高版本)中最简单的方法是什么?
const obj = {
one: 1,
two: 2,
three: 3
};
Run Code Online (Sandbox Code Playgroud)
我试过这个,但我猜它不起作用,因为这是计算键的语法:
const arr = [1,2,3];
const obj = {
[one, two, three] = arr
};
Run Code Online (Sandbox Code Playgroud)
小智 26
您不仅可以将变量分配给变量,还可以分配给现有对象:
const arr = [1,2,3], o = {};
({0:o.one, 1:o.two, 2:o.three} = arr);
Run Code Online (Sandbox Code Playgroud)
这没有任何额外的变量,并且重复性较低.但是,如果您非常关注它,它还需要两个步骤.
我不确定这是否有帮助,因为你提到了计算属性?!
我不相信有任何结构/解构解决方案只需一步即可完成.我在这个问题上想要类似的东西.旧:=草案提案在新提案清单中似乎没有支撑,所以我认为现在没有太多活动.
但是,您不需要一个,因为您无论如何都要对对象键进行硬编码,您只需使用普通对象初始值设定项:
const arr = [1,2,3];
const obj = {
one: arr[0],
two: arr[1],
three: arr[2]
};
console.log(obj);Run Code Online (Sandbox Code Playgroud)
有一个两步解决方案与解构,但当然,它不会给你任何东西,它会产生不必要的变量,所以我不推荐它.为了完整性:
const arr = [1,2,3];
const obj = {
one: arr[0],
two: arr[1],
three: arr[2]
};
console.log(obj);Run Code Online (Sandbox Code Playgroud)
通过解构,您可以创建新变量或分配给现有变量/属性。但是,您不能在同一条语句中声明和重新分配。
const arr = [1, 2, 3],
obj = {};
[obj.one, obj.two, obj.three] = arr;
console.log(obj);
// { one: 1, two: 2, three: 3 }Run Code Online (Sandbox Code Playgroud)
使用解构赋值可以从数组中赋值给一个对象
请试试这个例子:
const numbers = {};
[numbers.one, numbers.two, numbers.three] = [1, 2, 3]
console.log(numbers)Run Code Online (Sandbox Code Playgroud)
归功于http://javascript.info/的男孩,我在那里找到了一个类似的例子。此示例位于http://javascript.info/destructuring-assignment左侧部分的“分配给任何内容”中
| 归档时间: |
|
| 查看次数: |
7199 次 |
| 最近记录: |