Amy Chun Amy Chun - 5 months ago 9
Javascript Question

Javascript : generate random number function and push into array

I'm trying to push a random number of bunnies into a canvas from 1~10 in Javascript.
However, the

Math.random()
method doesn't seem to be working. It just gives me one bunny. What am I doing wrong?

var field = [];

var randomNum = Math.floor(Math.random() * 10);

field.push(randomNum * new Bunny());

function Bunny() {
...
}

Answer

It won't give you any bunnies at all. randomNum * new Bunny() will be NaN1, because you're trying to multiply an object with a number.

If you want multiple bunnies, you have to create them, probably in a loop:

var field = [];

var randomNum = Math.floor(Math.random() * 10);
for (var n = 0; n < randomNum; ++n) {          // Loop
    field.push(new Bunny());                   // creating and pushing
}                                              // multiple bunnies

function Bunny() {
// ...
}

1 Or a number, if you've overridden valueOf on Bunny.prototype, which seems unlikely.