console.log()是web开发人员工作中的好朋友。但是你知道控制台包含的不仅仅是console.log()吗?这篇文章要讨论的就是JavaScript中的控制台。
" q$ P9 ?+ s4 D9 t 简介
8 S2 v5 K) a. K O Web控制台是一个工具,主要用于记录与网页相关的信息,例如:网络请求、JavaScript安全错误、警告、CSS等。它使我们能够通过在网页内容中执行JavaScript表达式来与网页交互。
- O, b$ ]; D+ N& c% D 控制台的类型
' x$ {$ v7 b h1 X: i console.log() console.error() console.warn() console.clear() console.time() console.table() console.count() console.group()
6 V# S0 @" ^4 L6 T 1. console.log()
; b9 u8 i$ {" Q' ?1 H$ s 主要用于将输出信息打印到控制台。log()中可以放入任何类型,无论是强类型、数组、对象、还是布尔值等。
% n/ }( |' t# E; u) k- j //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()
% ~% W% b" _& R7 [6 X8 w/ { 2. console.error() / `4 n# d! m4 o' l. S% @
此方法用于将错误消息记录到控制台。在测试代码时很有用。默认情况下,错误消息将突出显示为红色。
s+ J! S$ c$ K5 v* h // console.error() method
console.error('This is a sample Error')
# p" x3 n( ~5 G5 H' F9 [# u
3. console.warn()
$ b/ b7 P6 d g' ]- p/ |' h) {" t 用于将警告消息记录到控制台。默认情况下,警告消息将突出显示为黄色。2 a; E" e4 s/ Q' B& B
// console.warn() method
console.warn('This is a sample Warning')
! t( P9 c) w$ o/ f) p0 W- `2 o$ A 4. console.clear() , p# t3 w% K4 s4 N; ?, l* o1 n" Z
用于清除控制台信息。清除控制台时,如果是基于Chromium的浏览器,将打印一个简单的叠加文本,如下面的截图所示“Console was cleared”,而在Firefox中,则不会返回任何消息。: w) n9 ^( [' N- q9 V1 V
// console.clear() method
console.clear()
o; z* M B# h
5. console.time()和console.timeEnd()
+ \6 W4 f4 O$ u$ |# H 无论何时我们想知道一段代码或一个函数所需要花费的时间,都可以使用JavaScript控制台对象提供的time()和timeEnd()方法。关键是要有一个必须相同的标签,而里面的代码可以是任何东西(函数、对象、甚至直接console.log()都可以)。
9 i: W. n) |7 I' i I: L( S5 w // 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')
. b4 t$ g% J7 D) G 6. console.table()
9 o: F& w7 S. [; S1 j5 x. A 这个方法允许我们在控制台中生成表格。输入数据必须是数组或显示为表格的对象。# I6 f: x4 J0 l/ f: \
// console.table() method
console.table({a:1, b:2, c:3, d:4, e:5})
4 a! R1 a8 w( W1 O5 p
7. console.count()
! @0 A$ r0 J O9 G/ T6 ]+ \ 这个方法在调用时会将数字(调用次数)写入到控制台。
1 [* }8 {, ]$ O# Y% R: ~ // console.count() method
console.log('This is a sample count')
for(let i=0; i<10; i++){
console.count('This is iteration number', i)
}
9 s. W1 P x' ]+ Z' `3 I
8. console.group()和console.groupEnd()
. @3 M; g4 R2 T8 S4 s5 H2 c% C3 Z$ B 控制台对象的group()和groupEnd()方法允许我们将内容分组到单独的代码块中,并且这些代码块将缩进。和time()和timeEnd()一样,它们也接受值相同的标签。
' Q7 ^% w7 Q3 ^7 x // 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')
. y- [( V% Q" }2 H