能用js写一个随机选择吗不要用数字
当然可以,以下是一个使用数组来实现随机选择的 JavaScript 代码示例:
const options = ['apple', 'banana', 'orange', 'kiwi', 'grape'];
function randomSelect() {
const randomIndex = Math.floor(Math.random() * options.length);
return options[randomIndex];
}
console.log(randomSelect()); // 随机选择一个水果
该代码首先定义了一个包含多个选项的数组 options,然后定义了一个名为 randomSelect 的函数,该函数使用 Math.random() 方法生成一个 0 到 1 之间的随机小数,将其乘以 options.length 获取到一个介于 0 和数组长度之间的随机整数,最后返回 options 数组中对应的随机选项。
可以通过多次调用 randomSelect() 函数来进行多次随机选择
原文地址: https://www.cveoy.top/t/topic/cgLF 著作权归作者所有。请勿转载和采集!