你可以在这里看到我的代码:
this.tiles.forEach ( function($tile)
{
$tile.content.x = ( $tile.posY - $tile.posX ) * ($tile.map.tilesWidth/2) + ($tile.offsetX + $tile.map.offsetX);
$tile.content.y = ( $tile.posY + $tile.posX ) * ($tile.map.tilesHeight/2) + ($tile.offsetY + $tile.map.offsetY);
$tile.content.tile = $tile;
});
因此,对于我的数组tiles
中的每个块,我都做了一些计算。
我的数组中的每一项都有一个属性posX
和posY
。
我这里的问题是,如果我的数组中有很多瓦片,这个foreach需要很长时间才能执行。
我需要添加一个条件,并对每个posX在Xmin和Xmax之间的磁贴执行此操作,对于posY也是如此。
我怎样才能做到尽可能简单呢?为了节省最大可能的资源..谢谢!
在我的数组中添加一个if条件不是一个好的解决方案,因为foreach仍然会遍历整个数组。
发布于 2013-11-17 15:35:47
您可以使用filter
方法:
this.tiles
.filter ( function($tile)
{
return $tile.posX <= Xmin && $tile.posX >= Xmax &&
$tile.posY <= Ymin && $tile.posY >= Ymax;
})
.forEach ( function($tile)
{
$tile.content.x = ( $tile.posY - $tile.posX ) * ($tile.map.tilesWidth/2) + ($tile.offsetX + $tile.map.offsetX);
$tile.content.y = ( $tile.posY + $tile.posX ) * ($tile.map.tilesHeight/2) + ($tile.offsetY + $tile.map.offsetY);
$tile.content.tile = $tile;
});
但是一个简单的for
-loop会更有效:
for (var i = 0; i < this.tiles.length; i++)
{
var $tile = this.tiles[i];
if ($tile.posX <= Xmin && $tile.posX >= Xmax &&
$tile.posY <= Ymin && $tile.posY >= Ymax)
{
$tile.content.x = ( $tile.posY - $tile.posX ) * ($tile.map.tilesWidth/2) + ($tile.offsetX + $tile.map.offsetX);
$tile.content.y = ( $tile.posY + $tile.posX ) * ($tile.map.tilesHeight/2) + ($tile.offsetY + $tile.map.offsetY);
$tile.content.tile = $tile;
}
}
https://stackoverflow.com/questions/20032509
复制相似问题