Skip to content

console 与浏览器控制台

console 是 JS 的原生对象,常见用途:调试、命令行

静态方法

console.log

  • 任意个参数,连接起来输出
  • 自动换行
  • 支持占位符
    • %s 字符串 %d %i 整数 %f 浮点数 %o 对象
    • %c CSS代码字符串 支持对输出内容进行css渲染
  • 支持重写
  • 四类 .log .info .warn .error 对应浏览器控制台四个等级的打印
js
// 使用 %c 对输出内容进行css渲染
console.log(
    '%c在控制台面板的黄色背景红字',
    'color: red; background: yellow; font-size: 24px;'
)


// 重写log方法,添加时间戳
['log', 'info', 'warn', 'error'].forEach(function(method) {
    console[method] = console[method].bind(
        console,
    new Date().toISOString()
  );
});
console.log("出错了!"); // 2014-05-18T09:00.000Z 出错了!

console.table

用的不多

js
var p = {
    name: 'wang',
    age: 20
};
console.table(p);

console.count

输出某个函数被调用了几次

js
function render(){
    console.count('render')
    // do render
}

render() // render: 1
render() // render: 2

setTimeout(() => {
    render() // render: 3
}, 100);

console.dir

以树结构打印对象,话说,log 不就已经是树形的了吗

js
var p = {
    name: 'wang',
    age: 20
};
console.log(p);
console.dir(p)
console.dirxml(p)

console.assert

相当于在运行时,打印一下某个条件及其附带信息。

第一个参数是表达式,第二个参数是字符串。当第一个参数为false,会提示有错误,在控制台输出第二个参数,否则不会有任何结果。

console.time

这个还可以,在评估效率的时候,精确评估时间(ms)

js
console.time('Array initialize');
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
  array[i] = new Object();
};
console.timeEnd('Array initialize');
// Array initialize: 49.343994140625 ms

console.group

console.groupconsole.groupEndconsole.groupCollapsed() 用于将显示的信息分组。

console.trace

打印某个函数被调用时的调用栈。

js
function A() {
    const b = 1 + B()
}
function B() {
    const res = 1 + C()
}
function C() {
    console.trace()
    return 1
}
A()
/*
C	@	playground.html:19
B	@	playground.html:16
A	@	playground.html:13
(匿名)	@	playground.html:22
*/
//  playground.html:22 调用了,然后进入 A,然后进入B ,然后进入了C

console.clear

清除当前控制台的所有输出,将光标回置到第一行

控制台命令行

相对冷门,在浏览器控制台中内置的命令。

  • $_: 属性返回上一个表达式的值。
  • ${0} ${4}: 获取最近选中的k个元素。
  • ${selector}: 如果没引入Jquery的话,相当于querySelector
  • $$(selector): 相当于querySelectorAll
  • getEventListeners(object):获取object注册了的各种事件
  • monitorEvents(object[, events]): 监听特定对象上的特定事件

debugger

在js代码中添加debugger,相当于在浏览器开发者面板中,在源代码打断点