JavaScript Negative Array Indexes

January 15, 2009

Is nothing sacred?

~ aran$ js
Rhino 1.7 release 1 2008 03 06
js> var x = [1,2,3]
js> x[3] = 4
4
js> x
1,2,3,4
js> x[-1] = "what?"
what?
js> x
1,2,3,4
js> x.length
4
js> for(var i in x) {
> print("x[" + i + "] = " + x[i]);
> }
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = 4
x[-1] = what?

Advertisements

7 Responses to “JavaScript Negative Array Indexes”

  1. Greg Wilson Says:

    Is it casting -1 to unsigned int, then using that as an index? JS indices don’t have to be consecutive.

  2. aran Says:

    Rhino seems to cast all array indices to string.


    ~ aran$ js
    Rhino 1.7 release 1 2008 03 06
    js> var x = [1,2,3]
    js> x[-1] = "why?"
    why?
    js> x["-1"]
    why?
    js> x["0"]
    1
    js> for(var i in x) { print(typeof(i)); }
    string
    string
    string
    string

  3. Reynold Xin Says:

    I was going to say JavaScript treats all arrays as associative arrays and -1 is just another index.

  4. aran Says:

    @Reynold: The kicker is the unintuitive behaviour of toString and length.

  5. Learn JS properly before criticising it Says:

    You just don’t understand JS which is the problem.

    It is perfectly valid.

  6. wiseoldduck Says:

    http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/

    This link explains pretty well what is actually going on here.


Comments are closed.

%d bloggers like this: