以下是一个使用JavaScript实现的简单随机点名代码示例:
// 假设这是学生名单数组
const students = ['张三', '李四', '王五', '赵六', '孙七'];
function getRandomName(arr) {
const randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
const selectedStudent = getRandomName(students);
console.log('被点到名的同学是:', selectedStudent);
一、基础概念
students
数组存储了学生的名字。arr.length
,可以将这个随机数的范围映射到数组索引的范围。Math.random() * arr.length
得到的小数转换为有效的数组索引(整数)。二、优势
三、应用场景
四、可能遇到的问题及解决方法
students
数组为空,Math.random() * arr.length
会得到0,Math.floor()
后索引为0,但数组中没有元素,会导致返回undefined
。领取专属 10元无门槛券
手把手带您无忧上云