Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to create a zero filled JavaScript array?

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

like image 666
dil Avatar asked Aug 18 '09 18:08

dil


People also ask

How do you make an array filled with 0?

In JavaScript, you can use the Array. fill() method to populate an array with a zero or any other value like an object or a string. This method replaces all elements in an array with the value you want to populate the array with and returns the modified array.

Which is the most accurate way to write a JavaScript array?

The correct way to write a JavaScript array var txt = new Array("arr ","kim","jim"). JavaScript arrays are used to store multiple values in a single variable. Using an array literal is the easiest way to create a JavaScript Array.

What is the correct way to create a JavaScript array?

Creating an ArrayUsing an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

ES6 introduces Array.prototype.fill. It can be used like this:

new Array(len).fill(0); 

Not sure if it's fast, but I like it because it's short and self-describing.

It's still not in IE (check compatibility), but there's a polyfill available.

like image 180
Oriol Avatar answered Sep 22 '22 17:09

Oriol