Thursday, 3 February 2022

JS Math.random() select a random element from array

 https://www.geeksforgeeks.org/how-to-select-a-random-element-from-array-in-javascript/


    var arr = ["GFG_1", "GeeksForGeeks",
                "Geeks", "Computer Science Portal"];
  function random(mn, mx) {
            return Math.random() * (mx - mn) + mn;
        }
         
arr[Math.floor(random(1, 5))-1];



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

Math.random()

he Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) 

so 0.xxx -0.99999


Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}

No comments:

Post a Comment