Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how are negative array indexes interpreted [duplicate]

Tags:

javascript

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?

like image 300
akonsu Avatar asked Mar 10 '14 18:03

akonsu


1 Answers

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.

like image 129
Arjit Avatar answered Nov 15 '22 00:11

Arjit