比较一个字符串

时间:2013-02-17 05:17:48

标签: javascript

我有一些JavaScript代码根据Ajax请求的响应对象中的各种因素创建不同的消息。例如

if (response.correct_guess === true){
    message = "your guess was correct
 }

如果用户赢了游戏,则'won'键设置为'won'

won: "won"

因此我希望像这样设置消息

else if(response.won === "won") {
          message = "You finished with" + response.seconds + "left on the clock."

然而,这个“其他如果”没有被触发

我也试过“==”(即两个等号而不是三个)。你能解释一下我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您的代码含义:

if (response.correct_guess === true){
    message = "your guess was correct

}else if(response.won === "won") {
      message = "You finished with" + response.seconds + "left on the clock."
}

如果猜测正确,message = "your guess was correct,就是这样。如果猜测不正确,则表示用户赢了,message = "You finished with" + response.seconds + "left on the clock."

你忘记了如果控制进入第一个if,它将永远不会到达第二个if。在if-elseif链中,第一个if / elseif块控件进入的是它将进入的一个。我不认为你想要那个。你可能想要:

if (response.correct_guess === true){
    message = "your guess was correct

}
if(response.won === "won") {
      message = "You finished with" + response.seconds + "left on the clock."
}