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
Release: 2024-12-13 11:53:13
Original
188 people have browsed it

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);
Copy after login

This will produce the desired output:

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template