Randomizer始终返回第一个值

时间:2014-03-03 03:11:08

标签: javascript random

我母亲是老师,我决定让她成为一名随机的学生选择者(二年级)。我的问题是它不断归还一名学生。丹尼尔。我将其设置为向控制台登录返回的随机数,即使随机数不是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 + ".")
}

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

1 个答案:

答案 0 :(得分:6)

你的第一个错误就是写=,你的意思是==rand = 8表示“make rand的值为1”;你需要rand == 8,“rand是否等于8?”。

但是如果使用数组,那么你的程序会更容易,更简单。

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

(还有一个额外的JavaScript ===的怪癖,这在这里并不重要,但是后来可能会在众所周知的屁股中咬你,所以一定要学会以后的差别。实际上会更好使用===而不是==测试所有内容,直到您知道为什么使用==。)