0

How to print 20 random number numbers in JavaScript. Below code is not giving desired results.

/// for (var i = 0; i < 20; i++) { Math.random(); } /// //this is printing just one number instead of 20 random numbers.

2nd May 2017, 7:26 AM
Chetan Vashistth
Chetan Vashistth - avatar
4 Respostas
+ 15
for (var i = 1; i < 20; i++) { alert(Math.floor(Math.random() * 20) + 1); }
2nd May 2017, 7:32 AM
Maz
Maz - avatar
+ 4
// random numbers from 1 to 20 (non-repeat ver) var nums = []; for (var i = 0; i < 20; i++) { do { num = (Math.floor(Math.random() * 20) + 1); } while (nums.indexOf(num)!=-1) nums.push(num); } console.log(nums);
2nd May 2017, 8:06 AM
Calviղ
Calviղ - avatar
+ 4
If you want really random numbers, you should include the time and date function to calculate the results. If you do not, it will never be a real random result and you will receive an exact copy of a previous batch of numbers that you generated. Believe me when I say, I was facing the same dilemma about 30 years ago and could not find another solution for this dilemma. Hope that you figure it out and try my suggestion. Keep in touch...
2nd May 2017, 9:08 AM
🇺🇸 Anatoli🇧🇪🇪🇺 ,
🇺🇸 Anatoli🇧🇪🇪🇺 , - avatar
+ 2
Got it. Code console.log(Math.random()); is giving desired result.
2nd May 2017, 7:32 AM
Chetan Vashistth
Chetan Vashistth - avatar