Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic variable names based on count result [duplicate]

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++) {
    let SampleVariable[i] = "test";
}

ElementCount will later on be dynamic.

The result of the above function should look like this:

SampleVariable1 = "test"
SampleVariable2 = "test"

My code seems to be wrong - what do I have to change here? Solution can be native JS or jQuery as well.

Thanks a lot!

like image 988
JonSnow Avatar asked Aug 05 '26 15:08

JonSnow


1 Answers

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

1, eval solution:

const ElementCount = 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";
}
like image 150
kz-xu Avatar answered Aug 07 '26 03:08

kz-xu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!