1

If I make this line in C\C++:

int myArray[10] = { 0 }; // all elements 0

I will have an array of ten zeros. How can I make in the same mode an array in Javascript, without for loop and push commands?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
jdscardoso
  • 291
  • 3
  • 17

2 Answers2

3
  1. Create an array of 11 undefined elements
  2. join them by using 0 as string
  3. split the array by empty string
  4. Use map to convert the strings to number

var myArray = new Array(11).join('0').split('').map(Number);

console.log(myArray);
document.write('<pre>' + JSON.stringify(myArray, 0, 2) + '</pre>');
Tushar
  • 85,780
  • 21
  • 159
  • 179
2

Use this

Array(10).fill(0);

Reference https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Examples

ARIF MAHMUD RANA
  • 5,026
  • 3
  • 31
  • 58