As per my comment, your function does not currently return
any value, which is why the output of your function is undefined
.
Also, to make a random number you are better using Math.random()
which is a built-in function to accomplish this. An example would be:
function GetRandomInteger(a, b) {
return Math.round(Math.random() * (b - a) + a);
}
var randomInt = GetRandomInteger(1, 5);
console.log(randomInt );
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(1, 5));
This uses Math.random()
to make a random number between 0 and 1. It then multiplies this by the range between a
and b
, and then adds the minimum value a
. Finally, it uses Math.round()
to round the result to a whole number.
In the case of the example snippet above, this returns a number between 1 and 5 (inclusive).
If the case is that a
can be larger than b
sometimes, the following modification will permit this to work still:
function GetRandomInteger(a, b) {
if (a <= b) {
return Math.round(Math.random() * (b - a) + a);
} else {
return Math.round(Math.random() * (a - b) + b);
}
}
var randomInt = GetRandomInteger(1, 5);
console.log(randomInt );
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(1, 5));
console.log(GetRandomInteger(5, 1));
console.log(GetRandomInteger(5, 1));