- lodash provides _.random() method to generate number.
- It takes 3 parameter min,max and boolean flag.The boolean flag with true value indicates the output as floating point number.
- In this demo, “We will learn about random() method to generate a random number”.
- The following code shows the use of random() method.
<!DOCTYPE html> <html> <head> <script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script> <meta charset="utf-8"> <title>lodash random() method</title> </head> <body> <script> console.log("RandomNumber between 0 to 100: ",_.random(0, 100)); console.log("RandomNumber between 0 to 20: ",_.random(20)); console.log("Random Floating Number between 0 to 200",_.random(0, 200,true)); console.log("Random Floating Number between 0 to 300",_.random(300,true)); console.log("Random Floating Number between 3.1 to 4,1",_.random(3.1,4.1,true)); </script> </body> </html>
- The output of the code are printed in the console.Check the below JSBIN. lodash random() method
- Using the random method let’s develop a random color generator.The following code contains a method to generate a random color by using red,green and blue set to random() method.
<!DOCTYPE html> <html> <head> <script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script> <meta charset="utf-8"> <title>lodash random() method</title> </head> <body> <h1>Sandeep Kumar Patel</h1> <button onclick="applyRandomColor()">Apply Random Color</button> <script> //Generates random color function applyRandomColor(){ var red = _.random(0, 255), green = _.random(0, 255), blue = _.random(0, 255); document.querySelector("h1").style.color= "rgb("+red+","+green+","+blue+")"; } </script> </body> </html>
- The following JSBIN shows the output of the above code.