0

I have an array of objects and I'm trying to iterate through each object in the array. I need to call a method on each object. How should I go about doing this?

function basicBox(x,y,width,height,color) {
    this.color = color;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.draw = function() {
        g.drawStyle = this.color;
        g.drawRect(this.x,this.y,this.width,this.height);
    }
}

var boxes = [b1,b2,b3];

function run() {
    for (var i = 0; i < boxes.length; ++i) {
        boxes[i].update();
    }
}
royhowie
  • 11,075
  • 14
  • 50
  • 67
Juice
  • 1

1 Answers1

0

It think Array.map(), Array.reduce() and of course Array.forEach() can can help you with the stuff you are asking for. Using for or while loops is absolutely adequate to iterate Arrays, but it is worth to try a more functional approach, because it prevents from rewriting loops and lets you focus on the task, which should be done for each element.

If you like to iterate over properties of an Object, a for in loop is possible, but there is also Object.keys() what returns all the properties of the given object.

philipp
  • 15,947
  • 15
  • 61
  • 106