gpt4 book ai didi

javascript - 随机发生器总是返回第一个值

转载 作者:行者123 更新时间:2023-11-28 12:30:50 25 4
gpt4 key购买 nike

我的母亲是一名老师,我决定让她随机挑选学生(二年级)。我的问题是它不断返回一名学生。丹尼尔.我将其设置为将返回的随机数记录到控制台,即使随机数不是 1,它也总是返回 Daniel。这是一个足够简单的任务,至少我是这么认为的。背景信息——有26名学生,她在丹佛任教(人口众多,名字很多奇怪)。

  function studPick() {  
var random = Math.random() * 100 / 3.84615384615

var rand = Math.ceil(random * 1)/1;
console.log("rand = " + rand + ".");
if (rand = 1) {
var student = "Daniel";
}
else if (rand = 2) {
var student = "Judge";
}
else if (rand = 3)
{
var student = "Jonathan";
}
else if (rand = 4) {
var student = "John";
}
else if (rand = 5) {
var student = "Amethyst";
}
else if (rand = 6) {
var student = "Noah";
}
else if (rand = 7) {
var student = "Antonio";
}
else if (rand = 8) {
var student = "Ramon";
}
else if (rand = 9) {
var student = "Aidan";
}
else if (rand = 10) {
var student = "Manuel";
}
else if (rand = 11) {
var student = "Ingrid";
}
else if (rand = 12) {
var student = "Anastasia";
}
else if (rand = 13) {
var student = "Annabella";
}
else if (rand = 14) {
var student = "Christella";
}
else if (rand = 15) {
var student = "La'Kym";
}
else if (rand = 16) {
var student = "Isabella";
}
else if (rand = 17) {
var student = "Hadiyah";
}
else if (rand = 18) {
var student = "Jersey S";
}
else if (rand = 19) {
var student = "Aviana";
}
else if (rand = 20) {
var student = "Zion";
}
else if (rand = 21) {
var student = "Carlos";
}
else if (rand = 22) {
var student = "Loren";
}
else if (rand = 23) {
var student = "Irie";
}
else if (rand = 24) {
var student = "Trinidad"
}
else if (rand = 25) {
var student = "Jersey W"
}
else if (rand = 26) {
var student = "Stella"
}
else {
alert("An error has occured");
}
alert("Randomly picked student: " + student + ".")
}

编辑:我怀疑我的问题是我正在重新定义一个已经定义的变量。我会检查一下,如果这是解决方案,请删除我的问题。

最佳答案

你的第一个错误是在你的意思是==的地方写了=rand = 8 表示“使rand 的值为1”;而您想要 rand == 8,“rand 等于 8 吗?”。

不过,如果您使用数组,您的程序会变得更加简单和简短。

var students = ["Daniel", "Judge", "Jonathan"];
var randomStudentIndex = Math.floor(Math.random() * students.length);
var student = students[randomStudentIndex];

(JavaScript 有一个额外的怪癖,即 ===,这在这里并不重要,但稍后可能会咬你的屁股,所以稍后一定要了解其中的区别。实际上,最好使用 === 测试所有内容,而不是 ==,直到您知道为什么要使用 ==。)

关于javascript - 随机发生器总是返回第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22138024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com