Hamdi
Hamdi

Reputation: 197

Looping vars in js with structure

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>


Upvotes: 0

Views: 45

Answers (2)

yunzen
yunzen

Reputation: 33439

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)

Upvotes: 2

Clem
Clem

Reputation: 2312

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
}

Upvotes: -1

Related Questions