AshleysBrain AshleysBrain - 5 months ago 15
Javascript Question

How are floating point array indices interpreted?

I can't find any information on this, but suppose I have

var arr = [1, 2, 3];
var x = arr[1.5];


I assumed that Javascript would
floor
the index and returns the item at index 1, but it seems at least in Chrome it just returns
undefined
.

Is this correct? I can't find any standard or documentation that confirms this. It's actually really inconvenient if so because I assumed the round-down behavior allows you to pass any float in the range [0, n) to an array index, but it seems you'll silently break your arrays if you do floating point math which isn't rounded.

Edit: if anyone's maintaining a list of javascript gotchas, please add this one. Now I have to review 10k lines of javascript code to see where this assumption I made is quietly causing bugs!

Answer

According to MDN: Array, array items are actually properties, and properties are identified by strings.

Accessing arr[1.5] is therefore the same as accessing arr['1.5'], and Firefox does actually do it that way.

This code:

var x = [0,1,2,3,4,5];

x[1.5] = 42;

alert(x);
alert(x['1.5']);
alert(x['1.50']);

outputs:

 0, 1, 2, 3, 4, 5
 42
 undefined

So, the item accessed using a floating point value is a property identified by the string representation of the number. Note that accessing an item using '1.50' is not the same as accessing an item using '1.5', so the index is not converted to a number.

I tested this in Internet Explorer and Chrome also, and they both do the same as Firefox.