Javascript if / else Statement

时间:2015-09-17 01:06:11

标签: javascript

我的语法错误。我不知道自己哪里出错了。

// Check if the user is ready to play!
confirm("I am ready to play!");
var age = 13;
var age = prompt("What's your age?");
if(var age === 13)
{
   console.log("You are allowed to play but at your own risk.");
}
else
{
   console.log(Play on!");
}

2 个答案:

答案 0 :(得分:3)

您只需要使用var声明一个变量:

// Check if the user is ready to play!
confirm("I am ready to play!");
var age = prompt("What's your age?");
if (age === '13') { // age will be a string
    console.log("You are allowed to play but at your own risk.");
} else {
    console.log("Play on!");
}

您收到语法错误,因为您无法在if语句中声明变量。

另请注意,您错过了"中的console.log;这也会导致语法错误。

你也有几个逻辑问题。首先,age将是一个字符串,而不是整数,因此age === 13永远不会匹配。此外,将age初始化为13并立即重新分配是没有意义的。

答案 1 :(得分:0)

 //this is another solution
 confirm("I am ready to play!");
 var age = prompt("What's your age?");//input type will be string
 age = parseInt(age);                 //can convert to number by parseInt
 if( age === 13)
 {
alert("You are allowed to play but at your own risk.");
 }
 else
 {
 alert("Play on!");
 }