console.log()是web开发人员工作中的好朋友。但是你知道控制台包含的不仅仅是console.log()吗?这篇文章要讨论的就是JavaScript中的控制台。
0 x5 Y% |& ?/ J7 v& F9 X4 ]1 h: h8 o 简介
8 r1 _* L2 P( H& ^3 E& }# S9 v Web控制台是一个工具,主要用于记录与网页相关的信息,例如:网络请求、JavaScript安全错误、警告、CSS等。它使我们能够通过在网页内容中执行JavaScript表达式来与网页交互。4 U+ K6 D8 j! w
控制台的类型2 E+ A4 s; k) X1 J* [" y& @
console.log() console.error() console.warn() console.clear() console.time() console.table() console.count() console.group()& ~" }6 x% w+ K+ l) Z
1. console.log() ; Y8 l: `) L* r A2 a Y: j
主要用于将输出信息打印到控制台。log()中可以放入任何类型,无论是强类型、数组、对象、还是布尔值等。
+ H s: l- w. ] //console.log() method
console.log('string')
console.log(800)
console.log(true)
console.log(null)
console.log(undefined)
console.log({a:1, b:2}) // object inside log()
console.log([1,2,3,4]) // array inside log()
7 d3 Y4 y7 O9 z7 H5 y- h 2. console.error()
1 F, F* m5 U. V3 c i- F7 { 此方法用于将错误消息记录到控制台。在测试代码时很有用。默认情况下,错误消息将突出显示为红色。) a/ O H# N) U l9 W8 p0 R; c
// console.error() method
console.error('This is a sample Error')
% Y, w6 E" V# z$ X
3. console.warn() 2 y$ f3 Q9 V1 s
用于将警告消息记录到控制台。默认情况下,警告消息将突出显示为黄色。2 w7 h3 c; P% P( t
// console.warn() method
console.warn('This is a sample Warning')
$ ~& d, p! P5 T1 ]5 T7 K9 k 4. console.clear()
$ B) A0 T- f* _, l 用于清除控制台信息。清除控制台时,如果是基于Chromium的浏览器,将打印一个简单的叠加文本,如下面的截图所示“Console was cleared”,而在Firefox中,则不会返回任何消息。
; M, v! A( o4 R& x // console.clear() method
console.clear()
! H5 p% K! c7 ]+ r/ q. H i
5. console.time()和console.timeEnd()
& Q n, \: O* }: X 无论何时我们想知道一段代码或一个函数所需要花费的时间,都可以使用JavaScript控制台对象提供的time()和timeEnd()方法。关键是要有一个必须相同的标签,而里面的代码可以是任何东西(函数、对象、甚至直接console.log()都可以)。' C* v* P: f+ H6 t
// console.time() and console.timeEnd() method
// console.time() method
console.time("Let's see time console")
let time1 = function(){
console.log('time1 function is running')
}
let time2 = function(){
console.log('time2 function is running')
}
time1()
time2()
// console.timeEnd() method
console.timeEnd('Time Taken')
, r9 q% E* K! U1 p 6. console.table()
+ w# A3 z, a+ R+ m 这个方法允许我们在控制台中生成表格。输入数据必须是数组或显示为表格的对象。8 S) T$ L: x6 t( R% F! s
// console.table() method
console.table({a:1, b:2, c:3, d:4, e:5})
. D7 Y7 X4 R( N+ C 7. console.count() $ a% p3 c X0 }9 j
这个方法在调用时会将数字(调用次数)写入到控制台。% ]. R, R0 M( ]; t- P. Z
// console.count() method
console.log('This is a sample count')
for(let i=0; i<10; i++){
console.count('This is iteration number', i)
}
: Z: D1 N [: c2 E% S( Z) o6 f) c
8. console.group()和console.groupEnd()
4 l$ m/ I# `6 v! Z3 ?: C3 N 控制台对象的group()和groupEnd()方法允许我们将内容分组到单独的代码块中,并且这些代码块将缩进。和time()和timeEnd()一样,它们也接受值相同的标签。0 s% B, N, d( L! W3 b5 O* `+ B
// console.group() and console.groupEnd() method
// console.group() method
console.group('This is a sample group')
console.log('This is a sample group log')
console.warn('This is a sample group warning')
console.error('This is a sample group error')
// console.groupEnd() method
console.groupEnd('This is a sample group')
console.log('This is a new section')
6 x6 [6 ?/ p4 K: ~, `