Home >Web Front-end >JS Tutorial >Why Does `map()` Return Undefined Values on Arrays Created with `new Array(count)`?
Understanding the Behavior of map on Arrays Created with new Array(count)
When working with JavaScript arrays, it's worth noting a peculiar behavior exhibited by arrays created using the syntax new Array(count).
As demonstrated in the code snippet below, invoking map() on a sparse array (an array containing undefined elements) created with new Array(count) yields an array of undefined values:
var x = new Array(3); x.map(function() { return 0; }); // [undefined, undefined, undefined]
In contrast, performing the same operation on a dense array (an array with no undefined elements) of the same length works as expected:
var y = [undefined, undefined, undefined]; y.map(function() { return 0; }); // [0, 0, 0]
This distinction stems from the fact that new Array(count) creates a sparse array, meaning it does not assign default values to its elements. Consequently, map() cannot perform any operations on the undefined elements, resulting in an array of undefined values.
To overcome this issue, you can either use a literal array syntax to create a dense array or explicitly fill the sparse array with desired default values using methods like Array.prototype.fill().
The above is the detailed content of Why Does `map()` Return Undefined Values on Arrays Created with `new Array(count)`?. For more information, please follow other related articles on the PHP Chinese website!