Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/403.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript if/else语句_Javascript - Fatal编程技术网

Javascript if/else语句

Javascript if/else语句,javascript,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

我的语法有错误。我不知道我错在哪里

// 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!");
}

只需使用
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
语句中声明变量,因此会出现语法错误

另外,请注意,您在上一个
控制台.log中缺少一个
;这也会导致语法错误


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

您不能在if中声明变量statement@DaveAnderson这只是编解码器的一部分关于学习使用if/else语句的y课程。此外,“age”将是一个字符串,显式“==”将永远不匹配。
 //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!");
 }