javascript - 用 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() 方法的方法。
解决方案
添加一个匿名函数,该函数接受一个参数item
(或任何你想调用的参数),然后调用item.show()
:
grounds.forEach(item => item.show())
较旧的浏览器可能不支持箭头功能 - 在这种情况下,请改为:
grounds.forEach(function(item) {
item.show();
})
推荐阅读
- python - FileToGoogleCloudStorageOperator 的替代方案
- memory - 进程之间的内存空间如何保持不同?
- ios - 删除 UITableView 部分中的所有内容后结束编辑
- nuget - VSTS 更改为 DevOps,现在我们的 Nuget 包没有进行身份验证。我们做什么?
- c# - 我有两个 WPF 控件,但是当我刷新它们的数据绑定时,只有一个在刷新
- c# - 删除所有使用的引用
- php - PHP 致命错误:找不到类 'Microsoft\BingAds\Auth\OAuthWebAuthCodeGrant'
- javascript - 获取“ngbCollapse”,因为它不是“div”的已知属性。将组件移动到子模块后出错
- asp.net-mvc - 填充 DropDownListFor:HtmlHelper 不包含“DropDownListFor”的定义
- c++ - C++接口继承不同参数方法