0

我正在编写询问用户姓名和年龄的代码。

var name;
var age;

name = prompt("What is your name?");
age = prompt("What is your age?");

代码设置为向他们重复他们的姓名和年龄,然后如果年龄变量低于 50,它使用 if 语句向他们发送一条消息,说“你还年轻”。

不过,我有一个问题。我无法打印告诉用户他们输入的年龄和姓名的字符串。我收到一个语法错误,告诉我有一个意外的字符串。

问题代码是这样的:

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();
4

3 回答 3

2
console.log("Your name is " + name + " and you are " + age + " years old.");

要内联插入变量,您需要在前后都使用连接运算

于 2012-10-15T00:34:28.640 回答
1

你错过了两个,+一个name又一个age。请更正如下:

console.log("You're name is " +name + " and you are " +age+ "years old.");
于 2012-10-15T00:34:39.253 回答
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.");
于 2012-10-15T00:34:41.297 回答