Firebug represents (new Array(N))
as an array with N
undefined
s in it. I recently ran across a scenario that demonstrated that a sized array with all undefined
values in it is different from a newly constructed, sized array. I'd like to understand the difference.
Suppose you want to generate a list of random integers between 0 and 1000.
function kilorange() {
return Math.floor(Math.random() * (1001));
}
no_random_numbers = (new Array(6)).map(kilorange);
my_random_numbers = [undefined, undefined, undefined,
undefined, undefined, undefined].map(kilorange);
I would have expected no_random_numbers
and my_random_numbers
to be equivalent, but they're not. no_random_numbers
is another array of undefined
s, whereas my_random_numbers
is an array with six random integers in it. Furthermore, after throwing a console.count
statement into kilorange
, I learned that my function never gets called for the array created with the Array constructor.
What is the difference, and why does map
(and presumably other iterable methods) not treat the above arrays the same?
The ES standard (15.4.4.19) defines the algorithm for map
, and it's quite clear from step 8b that since your array doesn't actually have any of those elements, it will return an "empty" array with length 6.
As others have mentioned, it has to do with array objects in js being (unlike their rigid C counterparts) very dynamic, and potentially sparse (see 15.4 for the sparsity test algorithm).
When you use:
var a = new Array(N);
no values are stored in the new array and even the index "properties" are not created. That is why map
won't do a thing on that array.
The fact that Firebug does that is a bug/feature of the Firebug. You should remember that it's console is an eval
envelope. There are other bug/features in the Firebug console.
For example in Chrome console you'll see the above a
array as []
.
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