For example, I had an array with 3 numbers:
例如,我有一个包含3个数字的数组:
var arr = [124, -50, 24];
and I need to convert this array to the object:
我需要将此数组转换为对象:
{
x: 124,
y: -50,
z: 24
}
I don`t want to use "old-style" syntax for this, for example:
我不想为此使用“旧式”语法,例如:
{
x: arr[0],
y: arr[1],
z: arr[2]
}
so for now, I`m using that syntax:
所以现在,我正在使用这种语法:
const [x, y, z] = [...arr];
const obj = {x, y, z};
But, is there is any way to do this with a straight dectructuring array to object without need of temporary variables?
但是,有没有办法用直接的解构数组来对象而不需要临时变量?
1 个解决方案
#1
0
You can also do
你也可以这样做
const obj = {};
([obj.x, obj.y, obj.z] = arr);
to avoid the temporary variables, but I'd question whether that's an improvement.
避免临时变量,但我怀疑这是否有所改善。
#1
0
You can also do
你也可以这样做
const obj = {};
([obj.x, obj.y, obj.z] = arr);
to avoid the temporary variables, but I'd question whether that's an improvement.
避免临时变量,但我怀疑这是否有所改善。