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.