-1

Hello I want to init Array with 5 zero elements in JS. Without classic initiation var arr = [0, 0, 0, 0, 0]

I try some variant:

var arr = new Array(5).map(() => 0);
var arr = new Array(5).map(function () {return 0;});
var arr = Array(5).map(function () {return 0;});

but this examples are not working.

Vadim
  • 557
  • 8
  • 21

3 Answers3

3

Either use .fill:

const arr = new Array(5).fill(0);
console.log(arr);

or Array.from, which has a built-in map function you can pass as a second parameter:

const arr = Array.from({ length: 5 }, () => 0);
console.log(arr);

See MDN:

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).

Using Array.from as above assigns undefined values to each element of the array, whereas new Array does not, which is why you can map after Array.from but not after invoking the Array constructor.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You need use method fill for array's in initialization.

example:

var arr = new Array(5).fill(0);
Ilya Rogatkin
  • 69
  • 1
  • 7
0

May a for loop help you?

For(i=0; i<N; i++){
    array[i]=value;
}

For a 5 length array of 0 it becomes

for(i=0; i<5; i++){
    array[i]=0;
}
Mellgood
  • 195
  • 2
  • 12