3

I have some variables that their name ends with a number. now I need to change their values in a loop.
instead of putting all of the variables in the loop I was wondering if there is a way to generate the name of a variables in the loop? something like this maybe?

let bla1 = 0
let bla2 = 1
let bla3 = 2
...

for(var i = 0; i<somearray.lenght; i++){
  bla[i] += 1
}

I'm pretty sure I have seen something similar somewhere. what is the best way to do this?

Adrin
  • 585
  • 3
  • 11
  • 1
    If you have a bunch of variables with names ending in numbers they should be in an array like `bla = [0, 1, 2]` then access them with `bla[0]`. This will make *everything* easier. – Mark Sep 22 '18 at 00:02
  • **Take a look:** https://stackoverflow.com/questions/11807231/how-to-dynamically-create-javascript-variables-from-an-array – Ele Sep 22 '18 at 00:05

2 Answers2

2

You can't generate variable names in a loop, but you can use object properties to achieve desired results:

const variables = {}

for(var i = 0; i < somearray.length; i++){
  variables[`bla${i}`] = i
}

// later can be accessed like
console.log(variables.bla1)
Restuta
  • 5,855
  • 33
  • 44
1

You're thinking of an array:

let bla = [0, 1, 2];

for (let i = 0; i < bla.length; i++) {
  bla[i] += 1;
}
Harry Cutts
  • 1,352
  • 11
  • 25