Skip to content Skip to sidebar Skip to footer

Create Dynamic Variable Names Based On Count Result

I am trying to combine a string and number to a dynamiclly generated variable. Currently tried it this way: const ElementCount = 2; for (i = 1, i <= ElementCount, i++) { le

Solution 1:

solution is to use eval, but It's nasty code, Avoid using 'eval', just use an array or object.

1, eval solution:

constElementCount = 2;

for (let i = 1; i <= ElementCount; i++) {
    eval("let SampleVariable[" + i + "] = 'test'");
}

2, array solution:

const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
    Variables["SampleVariable" + i] = "test";
}

3, object solution:

const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
    Variables["SampleVariable" + i] = "test";
}

Solution 2:

There are few mistakes in your code

  1. You using comma , to separate the statements. You should use semicolon ;
  2. You are declaring SampleVariable inside the for loop so its not avaliable outside. Declare it outside the loop.
  3. You shouldn't use independent variable for this purpose as they just differ by 1. You should store them in array and use SampleVariable[number] to access them.
  4. You should initialize i = 0 otherwise the first element of SampleVariable will be undefined

constElementCount = 2;
letSampleVariable = [];
for (let i = 0; i < ElementCount; i++) {
    SampleVariable[i] = "test";
}
console.log(SampleVariable);

Solution 3:

This is my solution

const ElementCount = 2;

for(i = 1; i <= ElementCount; i++) {
    this['SampleVariable'+i] = "test";
}
SampleVariable1 // "test" (browser)this.SampleVariable2 // "test"

Post a Comment for "Create Dynamic Variable Names Based On Count Result"