示例: 从数组中获取随机项
// program to get a random item from an array function getRandomItem(arr) { // get random index value const randomIndex = Math.floor(Math.random() * arr.length); // get random item const item = arr[randomIndex]; return item; } const array = [1, 'hello', 5, 8]; const result = getRandomItem(array); console.log(result);
输出
'hello'
在上面的程序中,访问了数组中的随机项。
0 到 array.length 之间的随机数是使用 Math.random()
方法生成的。
Math.floor()
返回由 Math.random()
生成的最接近的整数值。
然后使用此随机索引访问随机数组元素。