0

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() {
...
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I think you should use 1 + Math.floor(Math.random() * 10)
@mortezaT: Indeed, if the goal is to have between 1 and 10 bunnies (inclusive), yes, we'd want the +1. If the goal is to have between 0 and 9 bunnies (inclusive), then we wouldn't.
@AmyChun: See mortezaT's comment above, you likely want +1 on the line generating the random number.
@T.J.Crowder Yes, I've noticed that during updating my code. Thanks for the tip, guys!
0
var field = [];

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

for (k=0; k<randomNum; k++)

{

field.push(new Bunny());

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.