如何向 console.log 添加变量?

我正在用 JavaScript 编写一个简单的游戏,但是在故事中我需要它说出玩家的名字。目前为止我所知道的是:

var name = prompt("what is your name?");


console.log("story" name "story);

第二行怎么写?或者还有别的办法。有没有可能在控制台上一行有2个 console.log();

300399 次浏览

Then use + to combine strings:

console.log("story " + name + " story");

console.log takes multiple arguments, so just use:

console.log("story", name, "story");

If name is an object or an array then using multiple arguments is better than concatenation. If you concatenate an object or array into a string you simply log the type rather than the content of the variable.

But if name is just a primitive type then multiple arguments works the same as concatenation.

You can pass multiple args to log:

console.log("story", name, "story");

It depends on what you want.

console.log("story "+name+" story") will concatenate the strings together and print that. For me, I use this because it is easier to see what is going on.

Using console.log("story",name,"story") is similar to concatenation however, it seems to run something like this:

 var text = ["story", name, "story"];
console.log(text.join(" "));

This is pushing all of the items in the array together, separated by a space: .join(" ")

You can use another console method:

let name = prompt("what is your name?");
console.log(`story ${name} story`);

Both console.log("story" + name + "story") and console.log("story", name, "story") works just fine as mentioned in earlier answers.

I will still suggest of having a habit of console.log("story", name, "story"), because, if trying to print the object contents, like json object, having "story" + objectVariable + "story" will convert it into string.

This will have output like : "story" [object Object] "story".

Just a good practice.

When using ES6 you can also do this:

var name = prompt("what is your name?");
console.log(`story ${name} story`);

Note: You need to use backticks `` instead of "" or '' to do it like this.

There are several ways of consoling out the variable within a string.

Method 1 :

console.log("story", name, "story");

Benefit : if name is a JSON object, it will not be printed as "story" [object Object] "story"

Method 2 :

console.log("story " + name + " story");

Method 3: When using ES6 as mentioned above

console.log(`story ${name} story`);

Benefit: No need of extra , or +

Method 4:

console.log('story %s story',name);

Benefit: the string becomes more readable.

You can use the backslash to include both the story and the players name in one line.

var name=prompt("what is your name?"); console.log("story"\name\"story");

You can also use printf style of formatting arguments. It is available in at least Chrome, Firefox/Firebug and node.js.

var name = prompt("what is your name?");


console.log("story %s story", name);

It also supports %d for formatting numbers