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!
-
What is the surprising part here for you? The use of arrays as array indices? It seems hacky, but it does work (for numbers). Could be useful for golfing, actually.John Dvorak– John Dvorak2014年05月30日 21:48:27 +00:00Commented May 30, 2014 at 21:48
-
What is the question here?John Dvorak– John Dvorak2014年05月30日 21:50:00 +00:00Commented May 30, 2014 at 21:50
-
The question is, how come that [x,y] is an array, if it is never declared like this, e.g.: var arr = [x,y]. And if it were an array, shouldnt the code be like this: poiints[arr[0],arr[1]]; ?user3629892– user36298922014年05月31日 14:54:40 +00:00Commented May 31, 2014 at 14:54
2 Answers 2
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 }
3 Comments
points[[ 1, 3 ]]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