首页 > 解决方案 > 用 forEach 重写 for 循环

问题描述

我想重写以下代码:

    for(i = 0; i < grounds.length; i++) {
        grounds[i].show();
    }

以某种方式使用 forEach 方法:

grounds.forEach(**what should i post here?**);

完整代码:

 class Ground {
        constructor(x, y, sizeX, sizeY) {
            this.x = x;
            this.y = y;
            this.sizeX = sizeX;
            this.sizeY = sizeY;
        }

        show() {
            ctx.fillStyle = "rgb(138, 75, 13)";
            ctx.fillRect(this.x, this.y, this.sizeX, this.sizeY);
        }
    }
}


let ground;
let grounds = [];

function generateGround() {
    for(i = 0; i < 10; i++) {
        ground = new Ground(0 + i * 40, canvas.height - 30, 40, 30);
        grounds.push(ground);
    }
}

generateGround();

function draw() {

    for(i = 0; i < grounds.length; i++) {
        grounds[i].show();
    }

    requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

我读了几个例子,但我找不到为每个地面元素执行 show() 方法的方法。

标签: javascriptarraysobjectecmascript-6

解决方案


添加一个匿名函数,该函数接受一个参数item(或任何你想调用的参数),然后调用item.show()

grounds.forEach(item => item.show())

较旧的浏览器可能不支持箭头功能 - 在这种情况下,请改为:

grounds.forEach(function(item) {
    item.show();
})

推荐阅读