有没有办法在 JavaScript 中使用一行代码来 console.log 多个变量?

Roa*_*rke -2 javascript console.log

我想做的是使用 console.log 打印一堆变量。

let country = "India";
let continent = "Asian";
let population = "1.3 Billion";
        `
Run Code Online (Sandbox Code Playgroud)

例如,我想一次打印所有这些。我不想控制台记录所有内容。有没有办法使用单个代码来完成此操作?

der*_*her 5

您可以将多个参数传递给console.log. 所以

let country = "India";
let continent = "Asian";
let population = "1.3 Billion";

console.log(country, continent, population)
Run Code Online (Sandbox Code Playgroud)

将打印所有三个字符串。

如果您想要更多格式选项,您可以使用模板字符串

let country = "India";
let continent = "Asian";
let population = "1.3 Billion";

console.log(`country: ${country}  continent: ${continent}  population: ${population}`)
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个包含变量作为属性的对象。

let country = "India";
let continent = "Asian";
let population = "1.3 Billion";

console.log({country, continent, population});
Run Code Online (Sandbox Code Playgroud)