In this case it returns only -1. It is possible to do in javascript
math object?
You need to use brackets ()
, in your case it resulted in Math.floor(Math.random() * 7-1 )
=> Math.floor(0.xxx-1 )
=> Math.floor(-0.xxx )
=> -1
Make it
Math.floor(Math.random() * (7-1) );
I want to random a numbers like this from -5....0....5.
First get a number between 0 and 5
Math.floor(Math.random() * (5-0) );
Then multiply the same by either 1 or -1 randomly
var value = Math.floor(Math.random() * (5-0) );
var sign = window.performance.now() % 2 == 1 ? 1 : -1; //get the current timestamp of the system in nanoseconds (something like 1512635632715) and checking if that number is even or odd
value *= sign ;
Added Demo with nano seconds instead of milliseconds
function generateRandom() {
var value = Math.floor(Math.random() * (5 - 0));
var sign = window.performance.now() % 2 == 1 ? 1 : -1;
value *= sign;
return value;
}
var arr = [];
for( var counter = 0; counter < 100; counter++)
{
arr.push(generateRandom());
}
console.log(arr);