0

I am filling an array with random numbers with a loop, but the random number is exactly the same for each item in the array, I think this is because of the seed value that Math.rand() uses. How can i get a different number each time?

for(var i = 0; i < 10; i++){
    number[i] = getRandom(0, 100);
}

function getRandom(a, b){
    var num = Math.floor((Math.random()*b)+a);
    return num;
}
3
  • 3
    I get different numbers for all 10 entries when I take the code you posted here and run it in my Chrome console. Commented Jan 2, 2014 at 12:31
  • If you are simply returning the variable after assigning, directly return like this return Math.floor((Math.random()*b)+a) Commented Jan 2, 2014 at 12:32
  • Math.random is seeded by the current time - what environment are you running it in...? Commented Jan 2, 2014 at 12:41

2 Answers 2

1

Works fine for me:

http://jsfiddle.net/kzUUt/

You need to declare number though...

var number = new Array(10);
for(var i = 0; i < 10; i++)
{
    number[i] = getRandom(0, 100);
    console.log(number[i]);
}

function getRandom(a, b)
{
    var num = Math.floor((Math.random()*b)+a);
    return num;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here is working demo.

var number = new Array();
for (var i = 0; i < 10; i++) {
    number[i] = getRandom(0, 100);
}

function getRandom(a, b) {
    return Math.floor((Math.random() * b) + a);   
}
for (var j = 0; j < 10; j++) {
    alert(number[j]);
}

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.