在JavaScript中,console.log()
方法用于在浏览器的控制台中显示消息或变量。
下面是一个console.log()
的快速示例。您可以阅读本教程的其余部分了解更多细节。
示例
let message = "Hello, JavaScript!";
console.log(message);
// Output: Hello, JavaScript!
当我们运行上面的代码时,Hello, JavaScript!
将会显示在控制台中。
JavaScript console.log() 的语法
console.log(message);
这里,message 是一个值或一个 变量,它的值将被打印到控制台。
示例 1:JavaScript console.log() 方法
console.log("Good Morning!");
console.log(2000);
输出
Good Morning! 2000
这里,
console.log("Good Morning!")
会将字符串"Good Morning!"
打印到控制台。console.log(2000)
会将数字 2000 打印到控制台。
示例 2:打印存储在变量中的值
我们还可以使用console.log()
来显示存储在变量中的值。例如,
// store value in greet variable
const greet = "Hello";
// print the value of greet variable
console.log(greet);
输出
Hello
在这个例子中,我们使用console.log()
打印了 greet 变量的值,该变量被设置为字符串 "Hello"
。
更多关于 JavaScript console.log()
合并字符串和变量
在JavaScript中,您可以使用以下方法将字符串和变量合并到console.log()
中
1. 使用替换字符串
let count = 5;
console.log("There are %d items in your basket.", count);
// Output: There are 5 items in your basket.
在此示例中,我们在console.log()
中使用了替换字符串%d
来将 count 变量的值插入到打印的消息中。
这里,%d
是十进制或整数的占位符。
2. 使用模板文字
我们将一条消息放在两个反引号` `
之间,以利用 模板文字。例如,
let count = 5;
// use template literals
let message = `There are ${count} items in your basket.`;
console.log(message);
// Output: There are 5 items in your basket.
在这里,我们使用代码${count}
将 count 变量的值插入到消息中。
另请阅读