How are floating point array indices interpreted?

Viewed 6325

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!

4 Answers
Related