console.log详解

发布时间:2025-12-09 14:07:06 浏览次数:6

console.log方法用于在控制台输出信息。它可以接受一个或多个参数,将它们连接起来输出。

console.log('Hello World')// Hello Worldconsole.log('a', 'b', 'c')// a b c

console.log方法会自动在每次输出的结尾,添加换行符。

console.log(1);console.log(2);console.log(3);// 1// 2// 3

如果第一个参数是格式字符串(使用了格式占位符),console.log方法将依次用后面的参数替换占位符,然后再进行输出。

console.log(' %s + %s = %s', 1, 1, 2)//  1 + 1 = 2

上面代码中,console.log方法的第一个参数有三个占位符(%s),第二、三、四个参数会在显示时,依次替换掉这个三个占位符。

console.log方法支持以下占位符,不同类型的数据必须使用对应的占位符。

  • %s字符串
  • %d整数
  • %i整数
  • %f浮点数
  • %o对象的链接
  • %cCSS 格式字符串
var number = 11 * 9;var color = 'red';console.log('%d %s balloons', number, color);// 99 red balloons

上面代码中,第二个参数是数值,对应的占位符是%d,第三个参数是字符串,对应的占位符是%s

使用%c占位符时,对应的参数必须是 CSS 代码,用来对输出内容进行 CSS 渲染。

console.log(  '%cThis text is styled!',  'color: red; background: yellow; font-size: 24px;')

上面代码运行后,输出的内容将显示为黄底红字。

console.log方法的两种参数格式,可以结合在一起使用。

console.log(' %s + %s ', 1, 1, '= 2')// 1 + 1  = 2

如果参数是一个对象,console.log会显示该对象的值。

console.log({foo: 'bar'})// Object {foo: "bar"}console.log(Date)// function Date() { [native code] }

上面代码输出Date对象的值,结果为一个构造函数。

需要做网站?需要网络推广?欢迎咨询客户经理 13272073477