Home > database >  How can I set multiple varibles to multiple elements using for loops
How can I set multiple varibles to multiple elements using for loops

Time:07-08

I tried this, but I noticed that with this, the variables are not even declared

let idArray = ['one', 'two', 'three'];
let varArray = ['varOne', 'varTwo', 'varThree']
for (let i = 0; i < idArray.length; i  ) { 
  varArray[i] = document.getElementById(idArray[i])
}

CodePudding user response:

I don't realy understand the purpose of your code, but if you want to make a copy of array (not a reference) :

let arr = [1, 2, 3];
let copy = [...arr]; // this is a copy

CodePudding user response:

You can try:

let idArray = ['one', 'two', 'three'];
let varArray = ['varOne', 'varTwo', 'varThree'];

varArray.forEach( (varName, index) => {
   globalThis[varName] = idArray[index];
});

CodePudding user response:

  let idArray = ['one', 'two', 'three'];
    let varArray = ['varOne', 'varTwo', 'varThree'];
    let dict = {};
    for (let i = 0; i < idArray.length; i  ) { 
      dict[varArray[i]] = idArray[i]
    }
    
    console.log(dict)

or, if you want to use varOne or etc (that is not recommended):

let idArray = ['one', 'two', 'three'];
    let varArray = ['varOne', 'varTwo', 'varThree'];
    for (let i = 0; i < idArray.length; i  ) { 
      window[varArray[i]] = idArray[i]
    }
    
    console.log(varOne)

CodePudding user response:

As well not sure what you are trying to do exactly, maybe some more context would help. However, if you are trying to use a for-loop to populate the values of multiple variables according to the values within one of the arrays, why not just use an object?

e.g.

const obj = {};
let idArray = ['one', 'two', 'three'];
let varArray = ['varOne', 'varTwo', 'varThree'];

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

Otherwise, as already mentioned, you'd need to make the variables global and use window or global.

  • Related