简体   繁体   English

如何在js中使用'for循环'将多个变量分配给不同的值

[英]How to assign multiple variables to different value using 'for loop' in js

I was trying to assign multiple variables that i stored in an array to different variables that i stored in an array using the for loop .我试图将存储在数组中的多个变量分配给使用for 循环存储在数组中的不同变量。 Here is what i have tried but didn't get my wanted result.这是我尝试过的,但没有得到我想要的结果。 Instead it changed the variable array to the contents in the other array.相反,它将变量数组更改为另一个数组中的内容。

let varOne, varTwo, varThree;

let varArray = [varOne, varTwo, varThree]
let valueArray = ['value-one', 'value-two', 
'value-three']

for (let i = 0; i < varArray.length; i++) {
    varArray[i] = valueArray[i]
}

This is impossible.这是不可能的。 Variables can't be modified like this.不能像这样修改变量。 You just created a copy.您刚刚创建了一个副本。

I not really understand what do you want to solve, but with destructuring an array you can assing values to multiple variables.我不太明白您要解决什么问题,但是通过解构数组,您可以将值分配给多个变量。

 let [varOne, varTwo, varThree] = ['value-one', 'value-two', 'value-three']; console.log(varOne, varTwo, varThree);

Or you cam map all the arrays into key-value pairs of an object.或者,您可以将所有数组映射到对象的键值对中。

 let varArray = ["varOne", "varTwo", "varThree"] let valueArray = ['value-one', 'value-two', 'value-three'] let res = {}; varArray.forEach((key, i)=> { res[key] = valueArray[i]; }); console.log(res); // or in an array of object with map... let res2 = varArray.map((key, i)=>{ return {[key]: valueArray[i]}; } ); console.log(res2);

  • Use objects使用objects
let data={
 varOne:"value-one",
 varTwo:"value-two",
 varThree:"value-thress"
}

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

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