How does JavaScript determine if an array index is integer?

javascript

Solution

JavaScript arrays aren't really arrays, they're JavaScript objects that have prototype methods that cause them to act like arrays. `arr['one'] = 1` is valid JavaScript.

The way arr.length works is simply by looking at the array's keys, finding the largest number (JavaScript doesn't really do integers, just floats) and returning that number + 1.

try:

var arr = [];

arr.one = 1;
arr[8] = 1;
console.log(arr.length);

Problem

It seems that JavaScript's array indexes are actually all strings, so `a[0]` is the same as `a['0']` while `a[1.0]` is not `a[1]` but `a['1.0']`. But at the same time, array has a length property; it will be updated automatically when you modify value of integer keys. So how does JavaScript know the key is an integer and it needs to change length? If I do: ``` var a = 4/2; var b=8/4; var c = 2; var d= 1*2; ``` are `arr[2], arr[0+2], arr[1*2], arr[a], arr[b], arr[c], arr[d]` same thing? We often access array in a loop like this: ``` for (i=0; i<100; i++) { arr[i]=1; // this is a[0],a[1] right? arr[i+0.0]=1; // is this a[0] or a['0.0'] ? } ``` If I write this: ``` for (i=0.1; i<100; i+=0.1) { arr[i*10]=1; // what does it do? a[1] = 1, a[1.0]=1 or a[1.00000] = 1 ? } ``` what does the assignment in the loop do?

Original source