Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a zero filled JavaScript array of arbitrary length? [duplicate]

Tags:

javascript

What is the most efficient way to create a zero filled JavaScript array of arbitrary length ?

like image 319
user2814799 Avatar asked Nov 26 '13 16:11

user2814799


People also ask

How do you create a zero filled array of a desired length?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.

How do you create an array of certain lengths?

One common way of creating an Array with a given length, is to use the Array constructor: const LEN = 3; const arr = new Array(LEN); assert.

How do you declare an array with repeated values?

var repeatelem = function(elem, n){ // returns an array with element elem repeated n times. var arr = []; for (var i = 0; i <= n; i++) { arr = arr. concat(elem); }; return arr; }; javascript.

How do you duplicate an array in Javascript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


1 Answers

By default Uint8Array, Uint16Array and Uint32Array classes keep zeros as it's values, so you don't need any complex filling techniques, just:

var ary = new Uint8Array(10);  

all elements of array ary will be zeros by default.

like image 71
deadrunk Avatar answered Sep 29 '22 22:09

deadrunk