JavaScript 从数组中获取随机元素的程序
要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:
示例:从数组中获取随机项
// 程序用于从数组中获取随机项
function getRandomItem(arr) {
// 获取随机索引值
const randomIndex = Math.floor(Math.random() * arr.length);
// 获取随机项
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()
生成的最接近的整数值。- 然后使用这个随机索引来访问随机的数组元素。