Parametric variable names

Hi,
I would like to dynamically create (and use) variables where the name has an incremental suffix like Var1, Var2, Var3...
But my code is not working.

for(var i=0; i<=10; i++) {
    global.set(window['Var'+i],9);   
}

It would work without the window part. What's that about?

1 Like

Hello,
You can use a template string to set object properties in context parametrically as the first argument needs to be a string in the context set/get functions:

for(i=0;i<10;i++){
    global.set(`window.Var${i}`,9);
}

This will set the properties Var1, Var2, Var3 and so on of the object window in context. I think this is what you want.

Johannes

Would it not be better to use an array? That is what arrays are for.

The solution is without windows.

for(var i=0; i<=10; i++) {
    global.set(['Var'+i],9);   
}

Many thanks to all! Sorry for the dummy problem :slight_smile:

Colin, you are right but this variables will be arrays. So the best could be array of arrays... too much for me... I've tried before but without success, this solution is the workaround for my dummy skill. If you help me I can jump a step ahead :slight_smile:

Arrays of arrays can be confusing. The syntax to access an element is var[i][j].
You might be better to try the array of arrays route and come back when you have problems. You should end up with a better solution.

You don't need the square brackets. In fact I am not sure what effect they have, I am surprised it works.

True! Don't needs the square brakets but it works in both ways.

What is the point of getting the processor to waste its time building and then interpreting an array when it is not necessary?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.