简体   繁体   中英

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? Can you do:

world[x][y]

Thanks for your time.

First off, Arrays in JavaScript are just specialized objects . So when you have var a = ["entry"] and then go a[0] , you are accessing a property of a stored as "0" . Since all properties are converted to strings for JavaScript this means 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!

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! Now, you can go world[x][y] to get objects stored in those locations. Just as a little bit more information, the place holder is used to make the array actually have a length of Y as well.


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. Therein, the speed of access is limited by how the properties were chosen to be stored (as @zerms pointed out in the comments).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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