我正在使用代码学院网站学习JavaScript,每当我尝试if
/ else
计划时,它总会出现expected a identifier
。我不知道我做错了什么。我的程序看起来像这样:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log{"You are allowed to play but I take no responsibily";
}
else
{
console.log ;"Have fun playing"
}
答案 0 :(得分:4)
要调用console.log
函数,您需要围绕其参数(圆形)括号。你也错过了if条件后的左大括号:
confirm("Are you ready?")
var age = prompt("What's your age?");
if (age <= 18) {
console.log( "You are allowed to play but I take no responsibily" );
} else {
console.log( "Have fun playing" );
}
顺便说一下,如果if
,else
,for
等正文中只有一个语句,则可省略大括号。但是,使用适当的缩进很重要然后:
confirm("Are you ready?")
var age = prompt("What's your age?")
if (age <= 18)
console.log( "You are allowed to play but I take no responsibily" );
else
console.log( "Have fun playing" );
另请注意prompt()
正在返回一个字符串,在将其与18进行比较之前,您可能希望parse into a number:
var age = parseInt( prompt("What's your age?"), 10);
答案 1 :(得分:3)
if(confirm("Are you ready?"))
{
var age = prompt("What's your age?");
if (age <= 18)
{
console.log("You are allowed to play but I take no responsibily");
}
else
{
console.log("Have fun playing");
}
}
您需要使用正确的语法。例如,console.log是console.log("text")
答案 2 :(得分:0)
确保每个陈述后都有一个分号
confirm("Are you ready?")
var age = prompt("What's your age?")
需要阅读
confirm("Are you ready?");
var age = prompt("What's your age?");