Math.random继续回答相同的答案

Aid*_*dan 0 javascript

我仍然是编码和javascript的新手,但我将下面的代码编写为三向随机函数.一切似乎都运行良好,除了无论我运行多少次代码,返回都是插入的"c".我想知道是否有人可以给我一些关于如何解决这个问题的快速建议.谢谢.

var random = function() {
  var randomizer = function() {
    Math.random() * 100
  }

  if (randomizer <= 33) {
    var compDecision = "a"
  }
  else if (randomizer > 67) {
    var compDecision = "b"
  }
  else if (33 < randomizer <= 67) {
    var compDecision = "c"
  }

  document.write(compDecision)
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Tao 5

很快就会想到一堆东西:

1. JavaScript没有隐式返回

所以这不符合你的想法:

var randomizer = function() {
  Math.random() * 100
}
Run Code Online (Sandbox Code Playgroud)

该函数返回undefined.你需要:

var randomizer = function() {
  return Math.random() * 100
}
Run Code Online (Sandbox Code Playgroud)

2.在JavaScript函数调用中,括号不是可选的

所以这不会做你认为:

if (randomizer <= 33) {
    var compDecision = "a"
}
Run Code Online (Sandbox Code Playgroud)

你需要:

if (randomizer() <= 33) {
    var compDecision = "a"
}
Run Code Online (Sandbox Code Playgroud)

3. JavaScript没有三方比较

所以这不符合你的想法:

else if (33 < randomizer <= 67)
Run Code Online (Sandbox Code Playgroud)

你需要:

else if (33 < randomizer() && randomizer() <= 67)
Run Code Online (Sandbox Code Playgroud)

最后,正如其他人所提到的那样,定义randomizer为一个函数实际上从一开始就没有意义.为了使你的random函数能够做你想要的(生成'a','b'或者'c'概率大致相等),你真的想在函数的开头产生一个随机值并重用它:

function random() {
  var randomizer = Math.random() * 100;

  if (randomizer <= 33) {
    return 'a';
  } else if (randomizer <= 67) {
    return 'b';
  } else {
    return 'c';
  }
}

console.log(random());
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助.

  • 确保不要多次调用随机函数!那会打破条件逻辑 (2认同)