I recently discovered that .map
does not iterate of the undefined created by holed arrays, arrays whose individual indices were defined, but some weren't:
// Holed
var array = [];
array[0] = 1;
array[2] = 3;
array // => [1, undefined, 3];
// Not Holed
var array = [1, undefined, 3];
array // => [1, undefined, 3]; The "same" as Holed
When it comes to iteration, these two arrays, which should be identical, defined in different ways are iterated upon differently (see first sentance)
Thus are my questions,
undefined
. Am I correct? Is there any underlying explanation for this anomaly?Any help is very welcome. Thanks!
Is there any way to iterate over the holed arrays?
Majority (all?) built-in Array.prototype
functions skip holes in sparse arrays.
That means that if you want to get the undefined
value for the missing indexes - you need to turn that array into a non-sparse array first.
With the help of ES2015 you may use array iterators. The shortest way of doing it would be to use array spread syntax:
[...array]
Then you may apply a mapping operator to it [...array].map(handler)
I suspect that the exact bytes of these are actually different, and this strange behavior is due to how JavaScript displays these values which are not defined, not undefined. Am I correct? Is there any underlying explanation for this anomaly?
You are correct, it does not hold the undefined
values explicitly. As arrays in JS are actually so called "intrinsic objects" (or shorter - just objects), their indexes are simply the properties of those objects. So when you skip an index - that property is simply not set and does not exist.
It is the same as if you access a non existing object property:
var o = {};
o.foo // undefined
I just stumbled upon this, and none of these answers seemed appropriate. When I used
for( x of array)
I would get the appropriate number of loops, but no way to change the element (undefined and no index).
Going back to google, the next answer ref provided this as a solution:
for(const [key, value] of array.entries()) {
console.log(key+" : "+value)
}
Using entries
on the array allows us to get key/value pairs, even of undefined elements
1.As below:
// Holed
var array = [];
array[0] = 1;
array[2] = 3;
array // => [1, undefined, 3];
for(var i=0;i<array.length;i++) {
console.log(array[i])
}
map
,every
,forEach
,and so on have the same performance。The callback It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
Read more.
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