user3089871 user3089871 - 2 years ago 86
Javascript Question

How to push multiple zeros to an already existing array

I found on this link how to create arrays with a chosen number of zeros.
Most efficient way to create a zero filled JavaScript array?

But my question is, imagine i already have a array

var a = ['hihi','haha']

how can i add 12 zeros after my two first elements ? So that it becomes :

a = ['hihi','haha',0,0,0,0,0,0,0,0,0,0,0,0];

of course I could go for a

for(var i = 0; i < 12, i++){

but is there a one line method ? something like


Answer Source

You can use Array.prototype.concat() and Array.prototype.fill()

  1. Create an array with size 12 and fill 0 by using Array.prototype.fill()
  2. Then concatenate with existing array using Array.prototype.concat()

var a = ['hihi', 'haha'].concat(Array(12).fill(0));

document.write('<pre>' + JSON.stringify(a, null, 3) + '</pre>');

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download