Javascript foreach条件

Clé*_*aud 3 javascript performance foreach

在这里你可以看到我的代码:

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;
    });
Run Code Online (Sandbox Code Playgroud)

所以,对于我阵列中的每个瓦片,我都会tiles做一些计算.

我的数组中的每个项目都有一个attribut posXposY.

我的问题在这里,如果我的阵列中有很多瓷砖,这个foreach需要很长时间才能执行.

我需要添加一个条件,并为posX在Xmin和Xmax之间的每个tile执行此操作,对于posY也是如此.

我怎样才能尽可能简单地做到这一点?为了节省最大的资源..谢谢!

在我的数组中添加一个if条件不是一个好的解决方案因为foreach仍将遍历整个数组..

p.s*_*w.g 6

你可以使用这个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;
    });
Run Code Online (Sandbox Code Playgroud)

但是一个简单的for循环会更有效:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ClémentAndraud`.filter`遍历`tiles`中的每个项目并构造一个新数组,然后`.forEach`循环遍历结果数组中的每个项目.使用简单的for循环可以使您不必构造新数组或不必要的函数调用. (2认同)