-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_random()
More file actions
23 lines (14 loc) · 846 Bytes
/
Copy pathget_random()
File metadata and controls
23 lines (14 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//bing
const myArray = [1, 2, 3, 4, 5];
const randomElement = getRandomElementFromArray(myArray);
console.log(randomElement);
// This function takes an array as an argument and returns a random element from it. The Math.random() function generates a random number between 0 and 1 (exclusive). We multiply this number by the length of the array to get a random index within the bounds of the array. We then use Math.floor() to round down to the nearest integer, which gives us a valid index for the array.
function getRandomElementFromArray(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
//https://stackoverflow.com/questions/5915096/get-a-random-item-from-a-javascript-array
//copy to custom function
get_random = function (list) {
return list[Math.floor((Math.random()*list.length))];
}
get_random([2,3,5,7]) //usage