通过js中的数组属性方法进行迭代

Iterating through an arrays properties methods in js

本文关键字:方法 迭代 属性 数组 js 通过      更新时间:2023-09-26

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

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()可以帮助你完成你想要的东西。使用forwhile循环绝对足以迭代Arrays,但值得尝试一种功能性更强的方法,因为它可以防止重写循环,并让您专注于应该为每个元素执行的任务。

如果你想迭代对象的属性,for in循环是可能的,但也有Object.keys(),它返回给定对象的所有属性。