Skip to content

控制台对象方法 ​

在本节中,我们将介绍控制台和控制台对象方法。绝对的初学者通常不知道使用哪个:console.log()、document.write() 或 document.getElementById。

我们使用控制台对象方法在浏览器控制台上显示输出,我们使用 document.write 在浏览器文档(视口)上显示输出。这两种方法仅用于测试和调试目的。控制台方法是浏览器上最流行的测试和调试工具。当我们想要使用 JavaScript 与 DOM 交互时,我们使用 document.getElementById()。我们将在另一节中介绍 DOM。

除了著名的 console.log() 方法外,控制台还提供其他更多方法。

console.log() ​

我们使用 console.log() 在浏览器控制台上显示输出。我们可以替换值,也可以使用 %c 来设置日志输出的样式。

  • 在浏览器控制台上显示输出
js
console.log('30 Days of JavaScript')
sh
30 Days of JavaScript
  • 替换
js
console.log('%d %s of JavaScript', 30, 'Days')
sh
30 Days of JavaScript
  • CSS

我们可以使用 css 来设置日志消息的样式。复制以下代码并粘贴到浏览器控制台中查看结果。

js
console.log('%c30 Days Of JavaScript', 'color:green') // 日志输出是绿色的
console.log(
  '%c30 Days%c %cOf%c %cJavaScript%c',
  'color:green',
  '',
  'color:red',
  '',
  'color:yellow'
) // 日志输出绿色、红色和黄色文本

console.warn() ​

我们使用 console.warn() 在浏览器上给出警告。例如,通知或警告包的版本弃用或不良做法。复制以下代码并粘贴到浏览器控制台中查看警告消息。

js
console.warn('This is a warning')
console.warn(
  'You are using React. Do not touch the DOM. Virtual DOM will take care of handling the DOM!'
)
console.warn('Warning is different from error')

console.error() ​

console.error() 方法显示错误消息。

js
console.error('This is an error message')
console.error('We all make mistakes')

console.table() ​

console.table() 方法在控制台上将数据显示为表格。将表格数据显示为表格。console.table() 接受一个必需的参数 data,它必须是数组或对象,以及一个额外的可选参数 columns。

让我们首先从一个简单的数组开始。下面的代码显示一个有两列的表格。一个索引列显示索引,一个值列显示名称

js
const names = ['Asabeneh', 'Brook', 'David', 'John']
console.table(names)

让我们也检查一个对象的结果。这创建了一个有两列的表格:一个包含键的索引列和一个包含对象值的值列。

js
const user = {
  name: 'Asabeneh',
  title: 'Programmer',
  country: 'Finland',
  city: 'Helsinki',
  age: 250
}
console.table(user)

通过复制并粘贴到浏览器控制台来检查其余示例。

js
const countries = [
  ['Finland', 'Helsinki'],
  ['Sweden', 'Stockholm'],
  ['Norway', 'Oslo']
]
console.table(countries)
js
const users = [
  {
    name: 'Asabeneh',
    title: 'Programmer',
    country: 'Finland',
    city: 'Helsinki',
    age: 250
  },
  {
    name: 'Eyob',
    title: 'Teacher',
    country: 'Sweden',
    city: 'London',
    age: 25
  },
  {
    name: 'Asab',
    title: 'Instructor',
    country: 'Norway',
    city: 'Oslo',
    age: 22
  },
  {
    name: 'Matias',
    title: 'Developer',
    country: 'Denmark',
    city: 'Copenhagen',
    age: 28
  }
]
console.table(users)

console.time() ​

启动一个计时器,您可以使用它来跟踪操作需要多长时间。您为每个计时器提供一个唯一的名称,在给定页面上最多可以运行 10,000 个计时器。当您使用相同名称调用 console.timeEnd() 时,浏览器将输出自计时器启动以来经过的时间(以毫秒为单位)。

js
const countries = [
  ['Finland', 'Helsinki'],
  ['Sweden', 'Stockholm'],
  ['Norway', 'Oslo']
]

console.time('Regular for loop')
for (let i = 0; i < countries.length; i++) {
  console.log(countries[i][0], countries[i][1])
}
console.timeEnd('Regular for loop')

console.time('for of loop')
for (const [name, city] of countries) {
  console.log(name, city)
}
console.timeEnd('for of loop')

console.time('forEach loop')
countries.forEach(([name, city]) => {
  console.log(name, city)
})
console.timeEnd('forEach loop')
sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
Regular for loop: 0.34716796875ms
Finland Helsinki
Sweden Stockholm
Norway Oslo
for of loop: 0.26806640625ms
Finland Helsinki
Sweden Stockholm
Norway Oslo
forEach loop: 0.358154296875ms

根据上面的输出,常规 for 循环比 for of 或 forEach 循环慢。

console.info() ​

它在浏览器控制台上显示信息消息。

js
console.info('30 Days Of JavaScript challenge is trending on Github')
console.info('30 Days Of fullStack challenge might be released')
console.info('30 Days Of HTML and CSS challenge might be released')

console.assert() ​

如果断言为 false,console.assert() 方法会向控制台写入错误消息。如果断言为 true,则什么也不会发生。第一个参数是断言表达式。如果此表达式为 false,将显示"断言失败"错误消息。

js
console.assert(4 > 3, '4 is greater than 3') // 没有结果
console.assert(3 > 4, '3 is not greater than 4') // Assertion failed: 3 is not greater than 4

for (let i = 0; i <= 10; i += 1) {
  let errorMessage = `${i} is not even`
  console.log('the # is ' + i)
  console.assert(i % 2 === 0, { number: i, errorMessage: errorMessage })
}

console.group() ​

console.group() 可以帮助对不同的日志组进行分组。复制以下代码并粘贴到浏览器控制台中查看组。

js
const names = ['Asabeneh', 'Brook', 'David', 'John']
const countries = [
  ['Finland', 'Helsinki'],
  ['Sweden', 'Stockholm'],
  ['Norway', 'Oslo']
]
const user = {
  name: 'Asabeneh',
  title: 'Programmer',
  country: 'Finland',
  city: 'Helsinki',
  age: 250
}
const users = [
  {
    name: 'Asabeneh',
    title: 'Programmer',
    country: 'Finland',
    city: 'Helsinki',
    age: 250
  },
  {
    name: 'Eyob',
    title: 'Teacher',
    country: 'Sweden',
    city: 'London',
    age: 25
  },
  {
    name: 'Asab',
    title: 'Instructor',
    country: 'Norway',
    city: 'Oslo',
    age: 22
  },
  {
    name: 'Matias',
    title: 'Developer',
    country: 'Denmark',
    city: 'Copenhagen',
    age: 28
  }
]

console.group('Names')
console.log(names)
console.groupEnd()

console.group('Countries')
console.log(countries)
console.groupEnd()

console.group('Users')
console.log(user)
console.log(users)
console.groupEnd()

console.count() ​

它打印 console.count() 被调用的次数。它接受一个字符串标签参数。这对于计算函数被调用的次数非常有用。在以下示例中,console.count() 方法将运行三次

js
const func = () => {
  console.count('Function has been called')
}
func()
func()
func()
sh
Function has been called: 1
Function has been called: 2
Function has been called: 3

console.clear() ​

console.clear() 清除浏览器控制台。

🌕 继续保持良好的工作。继续努力,天空是极限!您刚刚完成了第13天的挑战,您在通往伟大的道路上前进了13步。现在为您的大脑和肌肉做一些练习。

练习 ​

练习:第1级 ​

  1. 将 countries 数组显示为表格
  2. 将 countries 对象显示为表格
  3. 使用 console.group() 对日志进行分组

练习:第2级 ​

  1. 10 > 2 * 10 使用 console.assert()
  2. 使用 console.warn() 写一个警告消息
  3. 使用 console.error() 写一个错误消息

练习:第3级 ​

  1. 检查以下循环之间的速度差异:while、for、for of、forEach

🎉 恭喜!🎉