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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With