Concatenate variable name

Good evening.
I’m trying for several days to do this thing but without success.
I should have a list of variables like this:

test1a = "a"
test1b = "b"
test1c = "c"
test2a = "a"
test2b = "b"
test2c = "c"
.....
test99a = "a"
test99b = "b"
test99c = "c"

I had thought about doing a for loop, but I can not concatenate “test” with x and with “a”/ “b”/“c”

Can anyone help me?
Thank you very much.

You mean a loop like this:(assuming all the variables are in global scope - otherwise you’d substitute the appropriate scope for window)

result = '';
for (i = 1, i < 100, i++) {
   result += window['test'+i+'a']+window['test'+i+'b']+window['test'+i+'c'];
}
console.log(result);
1 Like

Thanks for the quick answer. Now I have the computer turned off , i try tomorrow .

What are you trying to achieve with this?

I think perhaps what you’re really trying to do is to generate a dynamic object like this:

var items = [];
for (var i=0; i<100; i++) {
  items.push({
   a: 'a',
   b: 'b',
   c: 'c'
  });
}

Creating dynamic variables should usually be avoided.

1 Like

At first I thought this was a PHP variable variable question
http://php.net/manual/en/language.variables.variable.php
but then saw it was in JavaScript.

I suppose there might be a way to do similar with JavaScript, but why?

As best as I can recall, I’ve only ever needed to use PHP variable variables once in close to 20 years.

I agree - it is possible in JavaScript to use dynamic naming but it is very messy to do so and needing to generally indicates that the original design was wrong.

1 Like

If you are required to have a list of variables like that, as a learning exercise to help teach you different techniques, then so be it.

If you would like to learn of more appropriate techniques that are easier to work with, please let us know details of what you intend to use it for. We’ll be happy to help.

1 Like

It was not exactly what I wanted to do, but this answer to me was very helpful.
The code that I used to end is this:

for (i = 1; i < 100; i++) { window['test'+i+'a'] = "a"; window['test'+i+b'] = "b"; window['test'+i+c'] = "c";}

Thank you :slight_smile:

note that it will only work in legacy JavaScript - once you add ‘use strict’ to indicate modern JavaScript you can’t just add to the global namespace like that as all variables need to be declared before use (plus you shouldn’t be using the global namespace for variables in JavaScript anyway).

Why shouldn’t you use the global namespace for variables? Because it’s entirely possible for other scripts that you run to clobber those variables, resulting in unexpected behaviour.

1 Like

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