default array values

Viewed 108063

Is there a way to assign a default values to arrays in javascript?

ex: an array with 24 slots that defaults to 0

17 Answers
Array.prototype.repeat= function(what, L){
 while(L) this[--L]= what;
 return this;
}

var A= [].repeat(0, 24);

alert(A)

the best and easiest solution is :

Array(length of the array).fill(a default value you want to put in the array)

example

Array(5).fill(1)

and result will be

[1,1,1,1,1]

you can put any thing you like in it:

Array(5).fill({name : ""})

Now if you want to change some of the current value in the array you can use

[the created array ].fill(a new value , start position, end position(not included) )

like

[1,1,1,1,1].fill("a",1,3)

and output is

[1, "a", "a", 1, 1]

A little wordy, but it works.

var aray = [ 0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0,
             0, 0, 0, 0, 0, 0 ];

I personally use:

function replicate (n, x) {
  var xs = [];
  for (var i = 0; i < n; ++i) {
    xs.push (x);
  }
  return xs;
}

Example:

var hellos = replicate (100, "hello");

If you are using ES6 and up you can use

new Array(24).fill(0);

this also works:

Array.from({ length: 24}, () => 0)

No.

You have to use a loop.

var a = new Array(24);
for (var i = a.length-1; i >= 0; -- i) a[i] = 0;

Another way to achieve the same -

Array.from(Array(24),()=>5)

Array.from accepts a second param as its map function.

Syntax which i am using below is based on ECMA Script 6/es6

let arr=[];

arr.length=5; //Size of your array;

[...arr].map(Boolean).map(Number); //three dot operator is called spread Operator introduce in ECMA Script 6

------------Another way-------------

let variable_name=new Array(size).fill(initial_value)

for ex- let arr=new Array(5).fill(0) //fill method is also introduced in es6

Another way as per ECMA 5 or es5

var variable_name=Array.apply(null,Array(size)).map(Boolean).map(Number)

var arr=Array.apply(null,Array(5)).map(Boolean).map(Number);

All of them will give you same result : [0,0,0,0,0]

Related