JavaScript if语句比较不起作用

时间:2017-02-21 17:15:44

标签: javascript if-statement

if语句应该将buttonId值与randButtonId值进行比较,即使它们匹配,它仍然表示它是错误的。按钮从左到右按钮1,按钮2,按钮3,按钮4。

setBoard();
var randButtonId;
function setBoard(){
  var r = randomNumber(0 , 235);
  var g = randomNumber(0 , 235);
  var b = randomNumber(0 , 235);
  var color = rgb(r, g, b);
  var r2 = r + 20;
  var g2 = g + 20;
  var b2 = b + 20;
  var diffColor = rgb(r2 , g2 , b2);
  var randButtonId = "button" + randomNumber(1,4);
  setProperty("button1", "background-color", color);
  setProperty("button3", "background-color", color);
  setProperty("button2", "background-color", color);
  setProperty("button4", "background-color", color);
  setProperty(randButtonId, "background-color", diffColor);
  console.log("The correct one is: " + randButtonId);
}

function checkCorrect( buttonId ){
  console.log("Checking: " + buttonId);
  if( buttonId == randButtonId ) {
        console.log("You got it right!");
  } else {
        console.log("WRONG");
  }
  setBoard();
}
onEvent("button1", "click", function() {
  checkCorrect("button1");
});
onEvent("button2", "click", function() {
  checkCorrect("button2");
});
onEvent("button3", "click", function() {
  checkCorrect("button3");
});
onEvent("button4", "click", function() {
  checkCorrect("button4");
});

2 个答案:

答案 0 :(得分:1)

这可能与词法范围有关。考虑一下代码的这一部分:

var randButtonId = 'original value';

function setBoard() {
  // ...
  var randButtonId = 'something'
  console.log({
    randButtonId: randButtonId
  })
  // ...
}

function checkCorrect(buttonId) {
  console.log({
    randButtonId: randButtonId
  })
}

checkCorrect() // { "randButtonId": "original value" }
setBoard() // { "randButtonId": "something" }
checkCorrect() // { "randButtonId": "original value" }

您正在考虑使用第一行中声明的全局变量randButtonId的函数。但是'setBoard'函数使用var告诉解释器变量randButtonId是范围本地的。

TL; DR :如果您想在randButtonId中使用全局变量setBoard,请跳过var声明。

然而,使用全局变量是一种不好的做法,因为它会导致这种问题。一种更安全的方法是将所有逻辑封装在命名空间中。例如:

var ButtonChecker = {
  randButtonId: 'original value',
  
  setBoard: function() {
    // ...
    this.randButtonId = 'something'
    console.log({
      randButtonId: this.randButtonId
    })
    // ...
  },

  checkCorrect: function(buttonId) {
    console.log({
      randButtonId: this.randButtonId
    });
  }
};

ButtonChecker.checkCorrect(); // { "randButtonId": "original value" }
ButtonChecker.setBoard(); // { "randButtonId": "something" }
ButtonChecker.checkCorrect(); // { "randButtonId": "something" }

答案 1 :(得分:0)

您没有声明randomNumber函数

将此脚本放在头标记

<script>
function randomNumber(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>