繁体   English   中英

用forEach重写for循环

[英]Rewriting for loop with forEach

我想重写以下代码:

    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()方法的方法。

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

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

较旧的浏览器可能不支持箭头功能-在这种情况下,请执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM