user3629892
user3629892

Reputation: 3046

Understanding kinda weird javascript array notation

In a script I saw this:

function addToPoint(x, y) {
    x = Math.floor(x/SCALE);
    y = Math.floor(y/SCALE);
    if (!points[[x,y]]) {
      points[[x,y]] = 1;
    } else if (points[[x,y]]==10) {
      return;
    } else {
      points[[x,y]]++;
    }
  drawPoint(x*SCALE,y*SCALE, points[[x,y]]);

}

So what's happening, I think, is this:

points[[x,y]] = 1;

Here, the guy dynamically creates a field for the points-object (which was declared empty). By passing it like this, it gets converted to a string and the x and y params of the function will make up that field.

So, in effect, if i called addToPoints(3,4) the code results in this:

points["3,4"] = 1;

This is really weird to me: is [x,y] a legit array? What kinda notation is that? What's the rule behind that??

I played around with the code a bit and it seems like you can declare an array in JavaScript just by doing this:

[x,y]; 

Help, tips and clarification appreciated!

Upvotes: 0

Views: 100

Answers (2)

vittore
vittore

Reputation: 17589

I believe what you miss here is the fact that when you use something as a property name on a project it being converted to the string:

points[[x,y]] 

really doing

points[[x,y].toString()]

You can try to test it with

points[{}]

it will create key [object Object]

Reason to use it is that there is no support for two-dimensional arrays in javascript, however you can have array of arrays

And this little trick allow to use one dimensional array as a two-dimensional.

Here is funny trick:

Array.prototype.toString = function ( ) { return this.join(':') }

Now points[[x,y]] = 1

will create key x:y and not x,y

Upvotes: 1

Daff
Daff

Reputation: 44215

var arr = [ x, y ]; is simply how you declare an array in JavaScript with x and y as the first and second elements.

The second part points[[x,y]] is a little more confusing. Basically what happens is that the arr array gets converted into a string (something like [ 1, 2, 3 ] will become "1, 2, 3") which will then be used as the property name on the points object.

A little less terse (and with actual numbers instead of the x and y parameters) what happens looks somewhat like this:

var points = {};

var arr = [ 1, 3 ];
var key = arr.toString(); // '1, 3'

points[key] = 1; // { "1, 3": 1 }

Upvotes: 3

Related Questions