简体   繁体   English

Javascript:使用二维数组的最有效方法

[英]Javascript: Most Efficient Way To Use 2 Dimensional Arrays

I am currently making a tile map for a platformer. 我目前正在为平台游戏制作图块地图。

I know in other languages, when you refer to a 2 dimensional array, it is faster to do: 我知道用其他语言,当您引用二维数组时,这样做会更快:

world[y][x]

But, in javascript, does it matter? 但是,在javascript中,这有关系吗? Can you do: 你可以做:

world[x][y]

Thanks for your time. 谢谢你的时间。

First off, Arrays in JavaScript are just specialized objects . 首先, JavaScript中的数组只是专门的对象 So when you have var a = ["entry"] and then go a[0] , you are accessing a property of a stored as "0" . 所以,当你有var a = ["entry"]然后去a[0]您要访问的属性a存储为"0" Since all properties are converted to strings for JavaScript this means a[0] === a["0"] . 由于所有属性都已转换为JavaScript的字符串,因此这意味着a[0] === a["0"] Unlike in languages such as C++ when creating a double array you have to go darray[y][x] because of how the memory is created, with JavaScript we can assign an object to that location (since it is just another property) such that we can interpret how we want to! 与在创建双darray[y][x]数组时使用C ++之类的语言不同,由于创建内存的方式,您必须使用darray[y][x] ,使用JavaScript我们可以将对象分配给该位置(因为它只是另一个属性),使得我们可以解释我们想要的方式!

var world = [], // Start out with something empty.
    X = Y = 10; // Get dims.
// Fill that sucker up!
for(var i = 0; i < X; ++i)
{
    var x = [];
    for(var j = 0; j < Y; ++j)
    {
        // Forces a place holder in the array.
        x[j] = undefined;
    }
    world[i] = x;
}

And presto! 和presto! Now, you can go world[x][y] to get objects stored in those locations. 现在,您可以转到world[x][y]以获取存储在这些位置的对象。 Just as a little bit more information, the place holder is used to make the array actually have a length of Y as well. 与更多信息一样,占位符也用于使数组实际上也具有Y的长度。


Now, let's come back to the fact that an array is just a specialized object. 现在,让我们回到一个事实,即数组只是一个专门的对象。 This means we are accessing a property of the object world then again in the entry stored at that location. 这意味着我们要访问对象world的属性,然后再次访问该位置存储的条目。 Therein, the speed of access is limited by how the properties were chosen to be stored (as @zerms pointed out in the comments). 其中, 访问速度受选择存储属性的方式的限制(如@zerms在注释中指出)。

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

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