Home >Web Front-end >JS Tutorial >Why Does `new Array(count)` Behave Differently from Array Literals When Using `map()`?

Why Does `new Array(count)` Behave Differently from Array Literals When Using `map()`?

DDD
DDDOriginal
2024-12-13 11:53:13136browse

Why Does `new Array(count)` Behave Differently from Array Literals When Using `map()`?

Why Does Array Creation Affect Array Transformation?

In certain environments, creating an array using new Array(count) exhibits an unexpected behavior with the map method. Unlike arrays created with literal syntax (e.g., [undefined, undefined, undefined]), arrays constructed via new Array(3) do not correctly transform their elements using map.

This behavior is attributed to an unfilled array. When creating an array using new Array(count), the resulting array's elements remain undefined. This differs from arrays created using the literal syntax, which automatically initialize elements with undefined.

To work around this issue and ensure that map operates correctly, it is recommended to fill the array elements with any value, such as undefined, before attempting the transformation. The Array.prototype.fill() method can be used for this purpose.

For example, to create an array of the first 10 integers using new Array(count) and map:

let arr = new Array(10).fill(undefined).map((val, idx) => idx);

This will produce the desired output:

[0,1,2,3,4,5,6,7,8,9]

The above is the detailed content of Why Does `new Array(count)` Behave Differently from Array Literals When Using `map()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn