Home >Web Front-end >JS Tutorial >What\'s the Most Efficient Way to Create a Zero-Filled Array in JavaScript?

What\'s the Most Efficient Way to Create a Zero-Filled Array in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 07:22:14821browse

What's the Most Efficient Way to Create a Zero-Filled Array in JavaScript?

Most Efficient Way to Create a Zero Filled Array in JavaScript

It may be necessary in JavaScript to create an array of a specific length, with all its elements initialized to zero. This can be achieved in several ways, but some methods can be more resource-intensive or less clear than others.

Array.prototype.fill

The most efficient method, introduced in ES6, is to use the Array.prototype.fill method. It operates as follows:

new Array(len).fill(0);

Here, len represents the desired length of the zero-filled array. Array.prototype.fill accepts a single parameter, which specifies the value to fill each element with.

Example:

const myArray = new Array(5).fill(0);
console.log(myArray); // [0, 0, 0, 0, 0]

Other Methods

While using Array.prototype.fill is the preferred approach, there are alternative methods:

  • Array.apply:
Array.apply(null, {length: len}).map(Function.prototype.call, Number.prototype.valueOf);
  • new Array(len).fill():
[...Array(len)].map(() => 0);
  • Array.from(Array(len), () => 0):
Array.from({length: len}, () => 0);

The above is the detailed content of What\'s the Most Efficient Way to Create a Zero-Filled Array in JavaScript?. 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