Node.js的控制台console对象下的各种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/August_leo/article/details/82557720

1、console.log()方法

1.1 用于标准输出流的输出,即在控制台显示一行信息

示例:

C:\Users\Administrator>node
> console.log('node.js');
node.js
undefined
>

1.2 console.log()没有对参数的个数进行限制,当传递多个参数时,控制台输出时将以空格分隔这些参数

示例:

> console.log('node.js','is','powerful');
node.js is powerful
undefined
>

1.3 console.log()方法也可以利用占位符来定义输出的格式,如%d表示数字、%s表示字符

> console.log('%s%s%s','node.js','is','powerful');
node.jsispowerful
undefined
>
> console.log('%d','node.js');
NaN
undefined
> console.log('%d','node.js','is','powerful');
NaN is powerful
undefined
>

当使用%d占位符后,如果对应的参数不是数字,控制台将会输出NaN。

2、console.info()、console.warn()和console.error()方法

这三个方法的使用方法和console.log()一致,与console.log()的区别是console.warn()在浏览器控制台输出前加一个警告标志,console.error()在浏览器控制台输出前加一个错误标志

如图:

QQ截图20180909131550

3、console.dir()方法

用于将一个对象的信息输出到控件控制台。

示例:

> const obj = {
... name:'node.js',
... get:function(){
..... console.log('get');
..... },
... set:function(){
..... console.log('set');
..... }
... }
undefined
> console.dir(obj);
{ name: 'node.js', get: [Function: get], set: [Function: set] }
undefined
>

4、console.time()和console.timeEnd()方法

console.time()和console.timeEnd()方法主要用于统计一段代码运行的时间。console.time()置于代码起始处,console.timeEnd()方法置于代码结尾处。只需要向这两个方法传递统一个参数,就可以看到在控制台中输入了以毫秒计的代码运行时间。

示例:

> console.time('total time');
undefined
> console.time('time1');
undefined
> for(var i = 0;i<100000;i++){
... }
undefined
> console.timeEnd('time1');
time1: 64330.216ms
undefined
> console.time('time2');
undefined
> for(var i = 0;i<100000;i++){
... }
undefined
> console.timeEnd('time2');
time2: 16489.843ms
undefined
> console.timeEnd('total time');
total time: 134060.484ms
undefined

5、console.trace()方法

用于输出当前位置的栈信息,可以向console.trace()方法传递任意字符串作为标志,类似于console.time()中的参数。

示例:

> console.trace('trace');
Trace: trace
    at repl:1:9
    at ContextifyScript.Script.runInThisContext (vm.js:50:33)
    at REPLServer.defaultEval (repl.js:240:29)
    at bound (domain.js:301:14)
    at REPLServer.runBound [as eval] (domain.js:314:12)
    at REPLServer.onLine (repl.js:468:10)
    at emitOne (events.js:121:20)
    at REPLServer.emit (events.js:211:7)
    at REPLServer.Interface._onLine (readline.js:282:10)
    at REPLServer.Interface._line (readline.js:631:8)
undefined
>

猜你喜欢

转载自blog.csdn.net/August_leo/article/details/82557720
今日推荐