Home >Web Front-end >JS Tutorial >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(null, {length: len}).map(Function.prototype.call, Number.prototype.valueOf);
[...Array(len)].map(() => 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!