JavaScript 随机选择数组元素 - 简洁代码实现
这段代码演示了如何从一个给定的数组中随机选择元素,并确保每次选择的元素都不相同。
const options = ['apple', 'banana', 'orange', 'kiwi', 'grape'];
let i = -1;
let randomIndex;
function getRandomIndex() {
return Math.floor(Math.random() * options.length);
}
function randomSelect() {
do {
randomIndex = getRandomIndex();
} while (i === randomIndex);
i = randomIndex;
return options[i];
}
代码解释:
options数组: 定义了包含多个水果的数组。i变量: 用于存储上一次选择的索引,初始值为 -1。randomIndex变量: 用于存储随机生成的索引。getRandomIndex()函数: 生成一个介于 0 到数组长度之间的随机索引。randomSelect()函数:- 使用
do...while循环确保生成的随机索引与上次选择的不相同。 - 将
i设置为新的随机索引,以便下次调用时能够避免重复选择。 - 返回对应索引处的元素。
- 使用
使用方法:
console.log(randomSelect()); // 输出一个随机水果
console.log(randomSelect()); // 输出另一个随机水果(与上一次不同)
优化点:
- 使用
do...while循环简化代码逻辑,避免使用if...else语句。 - 将
randomIndex变量声明在函数外部,使其在每次调用randomSelect()时保持最新的值。 - 注释代码,使代码更易于理解。
原文地址: https://www.cveoy.top/t/topic/ntJD 著作权归作者所有。请勿转载和采集!