0

I am trying to find a better solution for adding objects to an array. The box objects are from a separate file and are pushed to the array one line at a time in a different file, as such:

function loadCols(){
collisionPoints.push(box1);
collisionPoints.push(box2);
collisionPoints.push(box3);
collisionPoints.push(box4);
collisionPoints.push(box5);
collisionPoints.push(box6);
collisionPoints.push(box7);
collisionPoints.push(box8);
collisionPoints.push(box9);
collisionPoints.push(box10);
};

I have tried using a for loop and concatenating the string "box" + i but this didn't work. I also tried adding them to an array in the file where the objects are created but I was not able to find a way of passing the array to the main file. Although this works I'm hoping there is a cleaner solution. Any help would be appreciated, cheers.

Rayon
  • 36,219
  • 4
  • 49
  • 76
user3355961
  • 725
  • 3
  • 16
  • 34

3 Answers3

1

If I understand you correctly you are looking for a way to use dynamic variables in a for-loop. If box1 and so on are global variables you can get them dynamically by accessing them as property of window:

window['box'+i]

See here: Use dynamic variable names in JavaScript

Community
  • 1
  • 1
jayms
  • 3,828
  • 2
  • 11
  • 18
1

You can get a variable from it's string name, by using the window object.

function loadCols(){
   for (var i=1; i<=numberOfBoxVars; i++) {
       collisionPoints.push(window["box" + i]);
   }
}

Alternatively, if your variable are defined within a closure and your loadCols function is defined within the same closure, you can use the "this" keyword in place of the window object.

(function() {
    var box1 = "1";
    var box2 = "2";
    ...

    function loadCols(){
        for (var i=1; i<=numberOfBoxVars; i++) {
           collisionPoints.push(this["box" + i]);
       }
    }
}); 
TheEllis
  • 1,666
  • 11
  • 18
0

If you send all the objects in a JSON array you could just do this:

var array = JSON.parse(boxesarray);
for(var i = 0;i< array.length; i++) {
    collisionPoints.push(array[i]);
}

But it would require you sending all the boxes in an array, if this is not possible please post code as to why it isn't and i will adapt my anwser.

namlik
  • 182
  • 1
  • 12
  • Would the load order of the javascript files make a difference? The file that creates the box objects is loaded before the main program which is load last. – user3355961 May 04 '16 at 12:11
  • Or is this created at the end of the objects file and can be accessed by the main file? – user3355961 May 04 '16 at 12:11
  • So if i understand right you have a .js that is creating the boxes and one that stores them in an array? I'll be able to give a detailed answer based on this. – namlik May 04 '16 at 12:15
  • Np i overlooked the fact that it was communication between two .js which as you have seen in the other answers, is easier. – namlik May 04 '16 at 12:19