console.log()是web开发人员工作中的好朋友。但是你知道控制台包含的不仅仅是console.log()吗?这篇文章要讨论的就是JavaScript中的控制台。
+ P$ x0 w" V* }2 _1 f0 s 简介
% c% D. G! c9 U3 f! U& H" [ Web控制台是一个工具,主要用于记录与网页相关的信息,例如:网络请求、JavaScript安全错误、警告、CSS等。它使我们能够通过在网页内容中执行JavaScript表达式来与网页交互。
7 `* c5 u. {) f: n$ ~+ |1 W, m( L 控制台的类型$ D6 g- B k! S. Z
console.log() console.error() console.warn() console.clear() console.time() console.table() console.count() console.group()/ T1 ?, C. p8 H T
1. console.log() $ W2 F; h2 u# g8 U0 ?
主要用于将输出信息打印到控制台。log()中可以放入任何类型,无论是强类型、数组、对象、还是布尔值等。
2 r" Y+ D. j3 g6 L0 T" F //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()
9 t4 S/ G# J3 H7 L) G: b
2. console.error() 6 f) H: Z/ @2 }3 E7 q
此方法用于将错误消息记录到控制台。在测试代码时很有用。默认情况下,错误消息将突出显示为红色。. F5 M A& L. R- t
// console.error() method
console.error('This is a sample Error')
9 k# H2 o0 v3 R
3. console.warn() 2 `( ?8 u5 T. I' A
用于将警告消息记录到控制台。默认情况下,警告消息将突出显示为黄色。( l. R3 y0 n1 K E/ v
// console.warn() method
console.warn('This is a sample Warning')
' t% f& x0 I8 u; Z3 A- h( H" g
4. console.clear()
6 y1 x Z" p& \) i: o/ a$ r+ M8 i0 ^ 用于清除控制台信息。清除控制台时,如果是基于Chromium的浏览器,将打印一个简单的叠加文本,如下面的截图所示“Console was cleared”,而在Firefox中,则不会返回任何消息。
' Y; b0 H3 R% f$ Y" ], D // console.clear() method
console.clear()
- i! ]" U4 B1 t. r) ~' U 5. console.time()和console.timeEnd() $ s9 o! l7 H4 A/ t0 x
无论何时我们想知道一段代码或一个函数所需要花费的时间,都可以使用JavaScript控制台对象提供的time()和timeEnd()方法。关键是要有一个必须相同的标签,而里面的代码可以是任何东西(函数、对象、甚至直接console.log()都可以)。% P6 ?; R- b @
// 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')
" n3 b) h+ `/ q6 B/ U% k( a# V
6. console.table()
6 h* H# y7 e% J 这个方法允许我们在控制台中生成表格。输入数据必须是数组或显示为表格的对象。
3 g, i6 B* v& u4 J# H, j" { // console.table() method
console.table({a:1, b:2, c:3, d:4, e:5})
: T: R) n O' ?* R9 b& K% Q
7. console.count() - s0 w. d' d7 j2 b' q
这个方法在调用时会将数字(调用次数)写入到控制台。
' b6 I c, ?3 I. o // console.count() method
console.log('This is a sample count')
for(let i=0; i<10; i++){
console.count('This is iteration number', i)
}
6 }# z5 c3 z2 H) b% P, k( b 8. console.group()和console.groupEnd() ; b+ S( T9 U# W: [( H
控制台对象的group()和groupEnd()方法允许我们将内容分组到单独的代码块中,并且这些代码块将缩进。和time()和timeEnd()一样,它们也接受值相同的标签。+ p& w2 t% R0 _+ U+ h% a0 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')
% t5 k5 }2 |. [0 K* F