我正在编写询问用户姓名和年龄的代码。
var name;
var age;
name = prompt("What is your name?");
age = prompt("What is your age?");
代码设置为重复他们的姓名和年龄,然后使用if语句向他们发送一条消息,说明“你年轻”,如果年龄变量低于50岁。
但是,我有一个问题。我无法打印告诉用户他们输入的年龄和姓名的字符串。我收到一个语法错误,告诉我有一个意外的字符串。问题代码是:
console.log("You're name is " +name " and you are " +age "years old.");
如果我只将一个变量打印到控制台,代码工作正常,如下所示:
console.log("You're name is " +name.);
希望你们能帮助我。
完整代码:
var name;
var age;
name = prompt("What is your name?");
age = prompt("What is your age?");
console.log("You're name is " +name " and you are " +age "years old.")
var printNameAndAge = function() {
if (age>50) {
console.log("Dang you're old.");
}
else {
console.log("You're pretty young, "+name);
alert("You're pretty young, "+name);
}
};
printNameAndAge();
答案 0 :(得分:2)
console.log("Your name is " + name + " and you are " + age + " years old.");
要插入变量内联,您需要在和之后使用连接运算符。
答案 1 :(得分:1)
+
之后你遗失了两个name
,age
之后遗漏了一个console.log("You're name is " +name + " and you are " +age+ "years old.");
。请更正如下:
{{1}}
答案 2 :(得分:1)
console.log("You're name is " +name " and you are " +age "years old.");
应该是
console.log("You're name is " +name +" and you are " +age+ "years old.");