javascript将值分配给另一个数组中的变量

时间:2020-10-21 06:12:39

标签: javascript

我该怎么做?

var x,y,z;
vars = [x,y,z];
vals = [55,66,77]

for(i in vars) {
    vars[i] = vals[i]
}

console.log(x) // undefined

我正在尝试分配55 to x66 to y77 to z,而无需使用解构,因此我可以像console.log(x)等那样引用它们。如何正确使用? / p>

1 个答案:

答案 0 :(得分:1)

问题出在逻辑上。

因此,基本上,当您使用vars [i] ='something'设置值时,实际上是将值设置为数组的第i个索引。

vars = [x,y,z]; - > compiles to -> var = [undefined,undefined,undefined]

and then if

vars[0] = 1;

vars =  [1,undefined,undefined]

But the value of X remains unchanged.