console.log()是web开发人员工作中的好朋友。但是你知道控制台包含的不仅仅是console.log()吗?这篇文章要讨论的就是JavaScript中的控制台。
0 D- x, R; h$ U( t# ] 简介 ( |: O" ?& S& p3 ` \
Web控制台是一个工具,主要用于记录与网页相关的信息,例如:网络请求、JavaScript安全错误、警告、CSS等。它使我们能够通过在网页内容中执行JavaScript表达式来与网页交互。
; }2 b2 P- S, I5 \ 控制台的类型+ L1 O4 f1 M1 r/ j
console.log() console.error() console.warn() console.clear() console.time() console.table() console.count() console.group()
- X- b# M2 O; Q' b$ H6 F$ F; ?1 S 1. console.log()
: D: X$ R6 O! S7 B8 D" ~. w3 C 主要用于将输出信息打印到控制台。log()中可以放入任何类型,无论是强类型、数组、对象、还是布尔值等。; `* e& W+ {+ p3 h; |
//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 I1 e- T5 f0 d) z
2. console.error() % K- K: F( M/ S, y( X0 q" A. W
此方法用于将错误消息记录到控制台。在测试代码时很有用。默认情况下,错误消息将突出显示为红色。$ C, i- g" A2 _: A0 C3 @# x
// console.error() method
console.error('This is a sample Error')
4 j" z8 `% S% a
3. console.warn() / d, Z* _5 V- w7 `0 z9 u5 ~% l! ?* a
用于将警告消息记录到控制台。默认情况下,警告消息将突出显示为黄色。
0 v2 e& }$ ^2 B* Z0 P" ] // console.warn() method
console.warn('This is a sample Warning')
$ N( @* k1 { a/ `" \( I: Z H
4. console.clear()
& x! S9 h# U1 s9 X! E) d' G- U 用于清除控制台信息。清除控制台时,如果是基于Chromium的浏览器,将打印一个简单的叠加文本,如下面的截图所示“Console was cleared”,而在Firefox中,则不会返回任何消息。
; l% r/ T% d4 }' r+ \ // console.clear() method
console.clear()
Y& w) D6 y0 |0 ^, Y: I6 H2 k
5. console.time()和console.timeEnd()
- y, V6 H. I2 A# N- B 无论何时我们想知道一段代码或一个函数所需要花费的时间,都可以使用JavaScript控制台对象提供的time()和timeEnd()方法。关键是要有一个必须相同的标签,而里面的代码可以是任何东西(函数、对象、甚至直接console.log()都可以)。0 ?, N8 w$ f+ k% \
// 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')
, w% g5 M& i0 \# y9 w* F 6. console.table() 1 K* T4 V4 c4 |6 \
这个方法允许我们在控制台中生成表格。输入数据必须是数组或显示为表格的对象。
2 ]' P/ B; c. j; _; c2 J6 X // console.table() method
console.table({a:1, b:2, c:3, d:4, e:5})
0 w( q) `' C. u2 e5 E
7. console.count() 7 @$ f1 g0 ^. ^6 H8 e9 G
这个方法在调用时会将数字(调用次数)写入到控制台。
, V" W( s) A! H9 Y8 r4 ~5 D // console.count() method
console.log('This is a sample count')
for(let i=0; i<10; i++){
console.count('This is iteration number', i)
}
S3 u3 M+ w& u4 e$ l$ i 8. console.group()和console.groupEnd() $ F* a; d/ l3 V ~. I9 Z
控制台对象的group()和groupEnd()方法允许我们将内容分组到单独的代码块中,并且这些代码块将缩进。和time()和timeEnd()一样,它们也接受值相同的标签。
" `8 u" Y6 k: i+ ? // 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')
' Q( j$ F$ ?1 ^3 ?$ X8 I+ t4 i