6

I create an array (in Chrome's console)

a = [1, 2, 3];
// [1, 2, 3]

then assign

a[-1] = 123;
// 123

this does not throw any error, but the resulting array does not get changed:

a
// [1, 2, 3]

but I can read the -1 property successfully:

a[-1]
// 123

How does indexing work with Javascript arrays? Why does not it show the new value that I have added? Apparently it treats it like a property. Why?

akonsu
  • 28,824
  • 33
  • 119
  • 194
  • Because the standard says so. ["A property name `P` (in the form of a `String` value) is an array index if and only if `ToString(ToUint32(P))` is equal to `P` and `ToUint32(P)` is not equal to `2**32−1`."](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4) – DCoder Mar 10 '14 at 18:56
  • Here is a link to another [stack overflow question](http://stackoverflow.com/questions/13618571/should-negative-indexes-in-javascript-arrays-contribute-to-array-length) that contains answers you might find useful. – theonlygusti Mar 10 '14 at 18:56
  • thanks. I got it now. This behaviour looks strange to me. – akonsu Mar 10 '14 at 18:59
  • The negative arrays are pretty much properties, "Behind the familiar object notation using the dot (i.e., obj.prop) JavaScript is actually accessing the property using association as in obj['prop']." - http://www.htmlgoodies.com/beyond/javascript/dont-fear-sparse-arrays-in-javascript.html Here is a link to another stack overflow question that contains answers you might find useful. – theonlygusti Mar 10 '14 at 19:02

1 Answers1

2

As Arrays are objects, It is because you can assign arbitrary properties to an array including negative numbers as well as fractions.

Negative indexes don't actually act like real indexes.

But it will not have any impact on length of array.

Arjit
  • 3,290
  • 1
  • 17
  • 18