console.log()是web开发人员工作中的好朋友。但是你知道控制台包含的不仅仅是console.log()吗?这篇文章要讨论的就是JavaScript中的控制台。
% m$ m0 K9 @# `$ L) @' V 简介 + N& C; |2 o0 Z" p2 s
Web控制台是一个工具,主要用于记录与网页相关的信息,例如:网络请求、JavaScript安全错误、警告、CSS等。它使我们能够通过在网页内容中执行JavaScript表达式来与网页交互。6 O5 B- E* y& z2 y( i
控制台的类型
; z0 a) @+ s) g; F# a7 U7 h console.log() console.error() console.warn() console.clear() console.time() console.table() console.count() console.group()
' S# b, C& u5 r+ m3 Z4 ]; E 1. console.log() # v. g P0 H* p5 E# ~8 W" e( `
主要用于将输出信息打印到控制台。log()中可以放入任何类型,无论是强类型、数组、对象、还是布尔值等。
) i8 C/ x( X7 m9 I/ |2 g' @! w7 U //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()
1 D% a% b& U: P+ d8 f4 x$ O
2. console.error() 9 e8 g) K2 @. ^0 z9 J0 g# c# H
此方法用于将错误消息记录到控制台。在测试代码时很有用。默认情况下,错误消息将突出显示为红色。
5 D# W; U' b6 M; s6 r% [ // console.error() method
console.error('This is a sample Error')
5 q* t1 C" V2 o" e* E; B% o7 F% J( ] 3. console.warn() 7 R4 T2 s2 \, e* S" ]4 A
用于将警告消息记录到控制台。默认情况下,警告消息将突出显示为黄色。 n# C, |& b! o# R) D
// console.warn() method
console.warn('This is a sample Warning')
; L5 E& J/ m% F' i3 f 4. console.clear() : a& j, `( E& ], s* U9 v
用于清除控制台信息。清除控制台时,如果是基于Chromium的浏览器,将打印一个简单的叠加文本,如下面的截图所示“Console was cleared”,而在Firefox中,则不会返回任何消息。; v* c1 l! ?8 j
// console.clear() method
console.clear()
1 w1 |1 r) h* s& y& U 5. console.time()和console.timeEnd()
, R# J2 `6 n P* G 无论何时我们想知道一段代码或一个函数所需要花费的时间,都可以使用JavaScript控制台对象提供的time()和timeEnd()方法。关键是要有一个必须相同的标签,而里面的代码可以是任何东西(函数、对象、甚至直接console.log()都可以)。) \) B$ L, ~* @& U
// 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')
" C9 @0 F, @& ]& ?9 j3 z# J* R
6. console.table()
9 {% `7 C: d/ G% `9 S0 n 这个方法允许我们在控制台中生成表格。输入数据必须是数组或显示为表格的对象。
* c$ B1 L/ ?: ` // console.table() method
console.table({a:1, b:2, c:3, d:4, e:5})
8 R+ ]! f! ~. `# `1 B" A6 O( P. U" ]
7. console.count() ' u2 h" q' M1 w2 R p, U) z
这个方法在调用时会将数字(调用次数)写入到控制台。" i c0 j& f. @5 X! L4 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)
}
' g" h- A, m( S7 g( u% p$ ` D 8. console.group()和console.groupEnd() * ~ c- w3 B6 U r& W4 o
控制台对象的group()和groupEnd()方法允许我们将内容分组到单独的代码块中,并且这些代码块将缩进。和time()和timeEnd()一样,它们也接受值相同的标签。) k; r3 H: O& A( g
// 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')
. H: {) a, p* E