0

I have a set of variables declared that has a structure, that is NameOfVar_NumberOfVar. Now I will be assigning equal values to all the declared variables. How do I add to create a loop to make the following assignment shorter?

I know the best way would be to declare an array, but I am continuing a code where arrays have not been used rather the following example has been used. So in such a case, I am trying to look for an optimized approach.

<script>

var ab_01;
var ab_02;
var ab_03;
var ab_04;

//tedious process
ab_01 = 10;
ab_02 = 10;
ab_03 = 10;
ab_04 = 10;

//optimized process?

for(var i = 0; i < 4; i++)
{
  //Assign [i] to the declared var
}

</script>


Hamdi
  • 187
  • 1
  • 2
  • 11
  • 2
    why not take an array instead? – Nina Scholz Apr 13 '21 at 08:01
  • [“Variable” variables in Javascript?](https://stackoverflow.com/q/5187530) – VLAZ Apr 13 '21 at 08:01
  • Thing is, I would definitely go for arrays. But I am continuing the script written by someone else and the person has assigned 10-15 buttons, variables, etc. and each of them have different functions. So I am trying to only optimize where I feel all the vars receive same function, value, etc. – Hamdi Apr 13 '21 at 08:03
  • An evil way would be the use of `eval()`. You should provide more than this code snippet for receiving suggestions for better way. The eval method should be avoided whenever you can. – Reporter Apr 13 '21 at 08:11

2 Answers2

2

Since global variables in JavaScript are only keys to the root object, you could add them with the Object Property Accessor [].

myObj = {}
// These do the same thing:
myObj.myKey = 'myVar'
myObj['myKey'] = 'myVar'
myObj['my' + 'Key'] = 'myVar'
myObj['m' + 'y' + 'K' + 'e' + y'] = 'myVar'
myObj['yourKey'.replace(/your/, 'my')] = 'myVar'

Since the root object in the browser is the window object (which has a reference to itself in the self key) , you could use that.

for (i = 1; i <=4; i++) {
self['ab_0' + i] = 10
}

console.log(ab_01, ab_02, ab_03, ab_04)
yunzen
  • 32,854
  • 11
  • 73
  • 106
-1

You can use eval to compose the var names.

for(var i = 0; i <4; i++) {
  eval(`ab_0${i} = 10`)
}

Or, as your vars are actually declared in the window scope, you can do:

for(var i = 0; i <4; i++) {
  window[`ab_0${i}`] = 10
}
Clem
  • 2,150
  • 15
  • 17