0

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. 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]
}
6
  • You can’t make an array of variables like that. Maybe reconsider your data structure. Commented Jul 8, 2022 at 19:18
  • so there's no way? Commented Jul 8, 2022 at 19:19
  • you are using array which is the same thing just directly assign value in array and access it with index, why you want to use thi short of structure , or else use javascript object, it contains key value. Commented Jul 8, 2022 at 19:20
  • No practical way, unless you choose to make globals and access them as properties… But you most likely do not need that nor is it a good idea. Consider using an object instead. Commented Jul 8, 2022 at 19:22
  • pls can i get an example Commented Jul 8, 2022 at 19:22

3 Answers 3

2

This is impossible. Variables can't be modified like this. You just created a copy.

Sign up to request clarification or add additional context in comments.

1 Comment

yh! that's what happened
2

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);

1 Comment

what if the code is very much and i want to assign them faster and easier?
0
  • Use objects
let data={
 varOne:"value-one",
 varTwo:"value-two",
 varThree:"value-thress"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.