0

I am new on JS and would like to set new variables automatically via For loop, by example:

var mybox0

var mybox1

etc...

var board = document.getElementById('board');
var boxes = [];

for(var i=0; i<9; i++){
    var myBox = document.createElement('div');
    board.appendChild(myBox);
    myBox.id = "box" + i;
    boxes.push(myBox);
}
F.Rahamim
  • 107
  • 1
  • 10
  • 4
    You're looking for arrays. – SLaks Oct 26 '18 at 15:11
  • What is the problem? Your code adds the element references to an array. You cannot create distinct variables with computed names, but you could create object properties like that. – Pointy Oct 26 '18 at 15:11
  • At the end of your loop, your `boxes` array contains the list of `div`s that you have declared inside the loop. You can access them with `boxes[0]` `boxes[1]` etc... but all the variables you have declared inside the block of the forloop are only available in the scope of that block – Mouradif Oct 26 '18 at 15:15
  • Look at this answer https://stackoverflow.com/a/5117172/3327441 – Gus de Boer Oct 26 '18 at 15:18
  • I would like to add an eventListener to each and everyone of them without declared again: var myBox0 = document.getElementById('box0'); – F.Rahamim Oct 26 '18 at 15:19

1 Answers1

1

Welcome to JavaScript! Always nice to have another in the fold.

The short answer is that this is not possible in JavaScript. You've really got two choices for this. You've already implemented the first one: arrays. It's a good option and the one I would go with personally.

An alternative, mentioned in the comments to your question, would be to use an object instead. The code would look something like this:

var board = document.getElementById('board');
var boxes = {};

for(var i = 0; i < 9; i++) {
    var myBox = document.createElement('div');
    board.appendChild(myBox);
    myBox.id = "box" + i;
    boxes['mybox' + i] = myBox;
}

You could then reference your variables like this:

boxes.mybox0; 
boxes.mybox1;

Instead of this:

boxes[0];
boxes[1];

My opinion of the code inside the for loop is that the array code is more readable than the object code. The code that makes use the generated object is equally readable to the array code. Furthermore, the array is more versatile as you can iterate over it more easily using functions like .map and .forEach.

So, I don't think there is anything to gain from using objects to do this and a bit to lose. Stick with the array.

Guy Royse
  • 2,739
  • 12
  • 9