0

Pretty new to javascript. The following code works perfectly for me. It is a reset button on a grid of 100 boxes. Each box is a movie clip called box1, box2 etc. On mouse release the simple loop operates to return all movie clips to first frame.

function mouseReleased() {
     for (var i = 1; i < 101; i++) {

         eval("box" + i).gotoAndStop(1);
     }
}

I have read a number of ways of replacing eval in this forum but I don't know enough javascript to apply them to my situation!

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
  • 1
    Put your boxes into an array, instead of using 101 numbered variables. – Bergi Apr 03 '18 at 09:40
  • We need to know how the box variables are defined. If they have global scope then you can just change the word eval for window and use square brackets... `window["box" + i].gotoAndStop(1);` – Reinstate Monica Cellio Apr 03 '18 at 09:40
  • This worked perfectly and I learnt a lot from this one. Hit a couple of Javascript guides based on your response here and I think the concept of object is starting to sink into my old brain (I'm 46 and don't think like computer code!) – Steven Murray Apr 04 '18 at 08:32

1 Answers1

0

You want to traverse an ordered list of objects. That screams for an array. You can define it like this:

 const boxes = [box1, box2, box3 /*...*/];

And then its as easy as:

 for(const box of boxes)
   box.gotoAndStop(1);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Previous response worked for me but I will be trying this as it seems very elegant. Knowing more than one way to do something never hurts. Thank you. – Steven Murray Apr 04 '18 at 08:34