语法错误:意外的令牌错误

时间:2013-06-26 22:21:44

标签: javascript

我在这里遇到语法错误,但无法理解原因。 TIA

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
console.log(computerChoice);

if(computerChoice >= 0.33) {
    computerChoice === "rock";
} else if ( computerChoice >= 0.34 && <= 0.66){
    computerChoice === "paper";
} else (computerChoice >= 0.67 && <= 1) {
    computerChoice === "scissors";
}

2 个答案:

答案 0 :(得分:4)

嗯,这里有几个问题。

句法:

} else ( computerChoice >= 0.67 && <= 1 ) {

应该是

} else if ( computerChoice >= 0.67 && computerChoice <= 1 ) {

} else {

但是在条件块中执行的东西实际上并没有做任何事情。您只是测试一些相等的东西,然后忽略测试的结果。

我想你想要的更接近:

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
console.log(computerChoice);

if ( computerChoice <= 0.33 ) {
    computerChoice = "rock";
} else if ( computerChoice >= 0.34 && computerChoice <= 0.66 ) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

答案 1 :(得分:1)

您缺少第二次逻辑比较的变量名称computerChoice)和代码最后部分的else而不是elseif。此外,您在应该使用赋值的位置使用类型/值比较。

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
console.log(computerChoice);

if(computerChoice >= 0.33) {
    computerChoice = "rock";
} else if ( computerChoice >= 0.34 && computerChoice <= 0.66){
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}