示例:从数组中获取随机项
// 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'
在上面的程序中,通过索引访问了数组中的一个随机项。 数组
- 使用
Math.random()
方法生成一个介于 0 和 array.length 之间的随机数。 Math.floor()
返回由Math.random()
生成的最近整数值。- 然后使用此随机索引来访问数组中的随机元素。
另请阅读