Results 1 to 3 of 3
Thread: return with javascript
-
March 29th, 2012, 05:17 AM #1
return with javascript
Hello,
I wish to make a variable which is a function that returns a random number when run.
for simple simon's sake, here is a silly example ..
Can someone help my syntax!?Code:var ran = function(){ Math.random()*1; return; } console.log(ran); // gives me my random number AND console.log(ran+" "+ran); // gives me two different random numbers
Thanks
-
March 29th, 2012, 06:50 AM #2Have a look at this tutorial: Random Numbers in JavaScriptCode:
var ran = function () { return Math.random(); }
-
March 29th, 2012, 07:15 AM #3
Further to jeancnicolas' example you need to use the brackets () to invoke the function:
There are a few things to keep in mind with the random number generator in JavaScript in that it's not truly random and if you are intending on using it where you want to be able to seed your own random numbers you can't (JavaScript seeds it's own random generator with the current time).Code:var ran = function(){ return Math.random()*1; } console.log(ran()); // gives me my random number AND console.log(ran()+" "+ran()); // gives me two different random numbers
Further reading:
http://blog.ginchen.de/en/2010/10/09...ll-keiner-ist/
http://stackoverflow.com/questions/1...ts-math-random
There are a few implementations I've seen for the Mersenne Twister algorithm if you need a number that is more truly random.

Reply With Quote


Bookmarks