Javascript 在js中迭代数组属性方法

Javascript 在js中迭代数组属性方法,javascript,Javascript,我有一个对象数组,我试图遍历数组中的每个对象。我需要对每个对象调用一个方法。我该怎么做呢 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

我有一个对象数组,我试图遍历数组中的每个对象。我需要对每个对象调用一个方法。我该怎么做呢

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();
    }
}
它认为Array.map、Array.reduce当然还有Array.forEach可以帮助您完成所需的任务。使用for或while循环绝对足以迭代数组,但值得尝试一种更实用的方法,因为它可以防止重写循环,并让您专注于应该为每个元素执行的任务

如果您想迭代对象的属性,可以使用for-in循环,但也有Object.keys返回给定对象的所有属性。

请参见此处:更新还是绘制?g是什么?