javascript控制台

by Darryl Pargeter

达里尔·帕格特(Darryl Pargeter)

如何充分利用JavaScript控制台 (How to get the most out of the JavaScript console)

One of the most basic debugging tools in JavaScript is console.log(). The console comes with several other useful methods that can add to a developer’s debugging toolkit.

JavaScript中最基本的调试工具之一是console.log() 。 该console附带了其他一些有用的方法,这些方法可以添加到开发人员的调试工具箱中。

You can use the console to perform some of the following tasks:

您可以使用console执行以下一些任务:

  • Output a timer to help with simple benchmarking输出计时器以帮助进行简单基准测试
  • Output a table to display an array or object in an easy-to-read format输出表以易于阅读的格式显示数组或对象
  • Apply color and other styling options to the output with CSS使用CSS将颜色和其他样式选项应用于输出

控制台对象 (The Console Object)

The console object gives you access to the browser’s console. It lets you output strings, arrays, and objects that help debug your code. The console is part of the window object, and is supplied by the Browser Object Model (BOM).

console对象使您可以访问浏览器的控制台。 它使您可以输出有助于调试代码的字符串,数组和对象。 consolewindow对象的一部分,由浏览器对象模型(BOM)提供 。

We can get access to the console in one of two ways:

我们可以通过以下两种方式之一来访问console

  1. window.console.log('This works')

    window.console.log('This works')

  2. console.log('So does this')

    console.log('So does this')

The second option is basically a reference to the former, so we’ll use the latter to save keystrokes.

第二个选项基本上是对前者的引用,因此我们将使用后者来保存击键。

One quick note about the BOM: it does not have a set standard, so each browser implements it in slightly different ways. I tested all of my examples in both Chrome and Firefox, but your output may appear differently depending on your browser.

关于BOM的简要说明:它没有设定的标准,因此每个浏览器以略有不同的方式实现它。 我在Chrome和Firefox中都测试了所有示例,但是输出结果可能会因浏览器而有所不同。

输出文字 (Outputting text)

The most common element of the console object is console.log. For most scenarios, you’ll use it to get the job done.

console对象最常见的元素是console.log 。 对于大多数情况,您将使用它来完成工作。

There are four different ways of outputting a message to the console:

有四种将消息输出到控制台的方式:

  1. log

    log

  2. info

    info

  3. warn

    warn

  4. error

    error

All four work the same way. All you do is pass one or more arguments to the selected method. It then displays a different icon to indicate its logging level. In the examples below, you can see the difference between an info-level log and a warning/error-level log.

所有四个工作方式相同。 您要做的就是将一个或多个参数传递给所选方法。 然后,它显示一个不同的图标来指示其日志记录级别。 在下面的示例中,您可以看到信息级日志和警告/错误级日志之间的区别。

You may have noticed the error log message - it’s more showy than the others. It displays both a red background and a stack trace, where info and warn do not. Though warn does have a yellow background in Chrome.

您可能已经注意到了错误日志消息-它比其他消息更加精美。 它显示红色背景和堆栈跟踪 ,而infowarn不显示。 虽然warn确实在Chrome中显示了黄色背景。

These visual differences help when you need to identify any errors or warnings in the console at a quick glance. You would want to make sure that they are removed for production-ready apps, unless they are there to warn other developers that they are doing something wrong with your code.

这些视觉上的差异有助于您快速识别控制台中的任何错误或警告。 您可能要确保将它们删除以用于生产就绪型应用程序,除非它们在那里警告其他开发人员它们对您的代码有误。

字符串替换 (String Substitutions)

This technique uses a placeholder in a string that is replaced by the other argument(s) you pass to the method. For example:

此技术在字符串中使用占位符,该占位符由传递给该方法的其他参数替换。 例如:

Input: console.log('string %s', 'substitutions')

输入console.log('string %s', 'substitutions')

Output: string substitutions

输出string substitutions

The %s is the placeholder for the second argument 'substitutions' that comes after the comma. Any strings, integers, or arrays will be converted to a string and will replace the %s. If you pass an object, it will display [object Object].

%s是逗号后第二个参数'substitutions'的占位符。 任何字符串,整数或数组都将转换为字符串,并替换%s 。 如果传递对象,它将显示[object Object]

If you want to pass an object, you need to use %o or %O instead of %s.

如果要传递对象,则需要使用%o%O代替%s

console.log('this is an object %o', { obj: { obj2: 'hello' }})

console.log('this is an object %o', { obj: { obj2: 'hello' }})

号码 (Numbers)

String substitution can be used with integers and floating-point values by using:

可以通过以下方式将字符串替换与整数和浮点值一起使用:

  • %i or %d for integers,

    %i%d代表整数),

  • %f for floating-points.

    %f为浮点数。

Input: console.log('int: %d, floating-point: %f', 1, 1.5)

输入console.log('int: %d, floating-point: %f', 1, 1.5)

Output: int: 1, floating-point: 1.500000

输出int: 1, floating-point: 1.500000

Floats can be formatted to display only one digit after the decimal point by using %.1f. You can do %.nf to display n amount of digits after the decimal.

使用%.1f可以将浮点数格式化为仅显示小数点后一位。 您可以执行%.nf以在小数点后显示n位数字。

If we formatted the above example to display one digit after the decimal point for the floating-point number, it would look like this:

如果将上面的示例格式化为浮点数的小数点后一位显示,则如下所示:

Input: console.log('int: %d, floating-point: %.1f', 1, 1.5)

输入console.log('int: %d, floating-point: %.1f', 1, 1.5)

Output:int: 1, floating-point: 1.5

输出int: 1, floating-point: 1.5

格式化说明符 (Formatting specifiers)

  1. %s | replaces an element with a string

    %s | 用字符串替换元素

  2. %(d|i)| replaces an element with an integer

    %(d|i) | 用整数替换元素

  3. %f | replaces an element with a float

    %f | 用浮点数替换元素

  4. %(o|O) | element is displayed as an object.

    %(o|O) | 元素显示为一个对象。

  5. %c | Applies the provided CSS

    %c | 应用提供CSS

字符串模板 (String Templates)

With the advent of ES6, template literals are an alternative to substitutions or concatenation. They use backticks (``) instead of quotation marks, and variables go inside ${}:

随着ES6的到来,模板文字可以替代或串联。 他们使用反引号(``)而不是引号,并且变量放在${}

const a = 'substitutions';
console.log(`bear: ${a}`);
// bear: substitutions

Objects display as [object Object] in template literals, so you’ll need to use substitution with %o or %O to see the details, or log it separately by itself.

对象在模板文字中显示为[object Object] ,因此您需要使用%o%O替换来查看详细信息,或单独记录它们。

Using substitutions or templates creates code that’s easier to read compared to using string concatenation: console.log('hello' + str + '!');.

与使用字符串连接相比,使用替换或模板创建的代码更易于阅读: console.log('hello' + str + '!');

漂亮的色彩插曲! (Pretty color interlude!)

Now it is time for something a bit more fun and colorful!

现在该换一些更有趣,更丰富多彩的东西了!

It is time to make our console pop with different colors with string substitutions.

现在是时候让我们的console以字符串替换的不同颜色弹出。

I will be using a mocked Ajax example that give us both a success (in green) and failure (in red) to display. Here’s the output and code:

我将使用一个模拟的Ajax示例,该示例使我们能够成功显示(绿色)和失败(红色)。 这是输出和代码:

const success = [ 'background: green', 'color: white', 'display: block', 'text-align: center'].join(';');
const failure = [ 'background: red', 'color: white', 'display: block', 'text-align: center'].join(';');
console.info('%c /dancing/bears was Successful!', success);console.log({data: { name: 'Bob', age: 'unknown'}}); // "mocked" data response
console.error('%c /dancing/bats failed!', failure);console.log('/dancing/bats Does not exist');

You apply CSS rules in the string substitution with the %c placeholder.

您可以使用%c占位符在字符串替换中应用CSS规则。

console.error('%c /dancing/bats failed!', failure);

Then place your CSS elements as a string argument and you can have CSS-styled logs. You can add more than one %c into the string as well.

然后将CSS元素作为字符串参数放置,您将拥有CSS样式的日志。 您也可以在字符串中添加多个%c

console.log('%cred %cblue %cwhite','color:red;','color:blue;', 'color: white;')

This will output the words ‘red’, ‘blue’ and ‘white’ in their respected colors.

这将以受尊重的颜色输出单词“红色”,“蓝色”和“白色”。

There are quite a few CSS properties supported by the console. I would recommend experimenting to see what works and what doesn’t. Again, your results may vary depending on your browser.

控制台支持很多CSS属性。 我建议您尝试一下,看看有什么用,什么没用。 同样,您的结果可能会因浏览器而异。

其他可用方法 (Other available methods)

Here are a few other available console methods. Note that some items below have not had their APIs standardized, so there may be incompatibilities between the browsers. The examples were created with Firefox 51.0.1.

这是其他一些可用的console方法。 请注意,以下某些项目的API尚未标准化,因此浏览器之间可能存在不兼容性。 这些示例是使用Firefox 51.0.1创建的。

断言() (Assert())

Assert takes two arguments — if the first argument evaluates to a falsy value, then it displays the second argument.

Assert有两个参数-如果第一个参数的计算结果为假值,则显示第二个参数。

let isTrue = false;
console.assert(isTrue, 'This will display');
isTrue = true;
console.assert(isTrue, 'This will not');

If the assertion is false, it outputs to the console. It’s displayed as an error-level log as mentioned above, giving you both a red error message and a stack trace.

如果断言为假,则输出到控制台。 如上所述,它显示为错误级别的日志,同时为您提供红色错误消息和堆栈跟踪。

Dir() (Dir())

The dir method displays an interactive list of the object passed to it.

dir方法显示传递给它的对象的交互式列表。

console.dir(document.body);

Ultimately, dir only saves one or two clicks. If you need to inspect an object from an API response, then displaying it in this structured way can save you some time.

最终, dir仅保存一两次单击。 如果您需要从API响应中检查对象,则以这种结构化的方式显示该对象可以节省一些时间。

表() (Table())

The table method displays an array or object as a table.

table方法将数组或对象显示为表。

console.table(['Javascript', 'PHP', 'Perl', 'C++']);

The array’s indices or object property names come under the left-hand index column. Then the values are displayed in the right-hand column.

数组的索引或对象属性名称位于左侧索引列下方。 然后,这些值将显示在右侧列中。

const superhero = {     firstname: 'Peter',    lastname: 'Parker',}console.table(superhero);

Note for Chrome users: This was brought to my attention by a co-worker but the above examples of the table method don’t seem to work in Chrome. You can work around this issue by placing any items into an array of arrays or an array of objects:

Chrome用户注意事项:一位同事引起了我的注意,但是以上table方法示例在Chrome中似乎不起作用。 您可以通过将任何项目放入数组数组或对象数组来解决此问题:

console.table([['Javascript', 'PHP', 'Perl', 'C++']]);
const superhero = {     firstname: 'Peter',    lastname: 'Parker',}console.table([superhero]);

组() (Group())

console.group() is made up of at least a minimum of three console calls, and is probably the method that requires the most typing to use. But it’s also one of the most useful (especially for developers using Redux Logger).

console.group()至少由至少三个console调用组成,并且可能是需要使用最多键入内容的方法。 但这也是最有用的工具之一(特别是对于使用Redux Logger的开发人员)。

A somewhat basic call looks like this:

一个基本的调用如下所示:

console.group();console.log('I will output');console.group();console.log('more indents')console.groupEnd();console.log('ohh look a bear');console.groupEnd();

This will output multiple levels and will display differently depending on your browser.

这将输出多个级别,并且将根据您的浏览器显示不同的内容。

Firefox shows an indented list:

Firefox显示缩进列表:

Chrome shows them in the style of an object:

Chrome以对象的样式显示它们:

Each call to console.group() will start a new group, or create a new level if it’s called inside a group. Each time you call console.groupEnd() it will end the current group or level and move back up one level.

每次对console.group()调用都会启动一个新的组,或者如果在组内调用了新的关卡。 每次调用console.groupEnd() ,它将结束当前组或级别并返回上一级。

I find the Chrome output style is easier to read since it looks more like a collapsible object.

我发现Chrome输出样式更易于阅读,因为它看起来更像一个可折叠的对象。

You can pass group a header argument that will be displayed over console.group:

您可以向group传递一个标题参数,该参数将显示在console.group

console.group('Header');

You can display the group as collapsed from the outset if you call console.groupCollapsed(). Based on my experience, this seems to work only in Chrome.

如果调用console.groupCollapsed()则可以从一开始就将组显示为折叠状态。 根据我的经验,这似乎仅在Chrome中有效。

时间() (Time())

The time method, like the group method above, comes in two parts.

与上面的group方法一样, time方法分为两个部分。

A method to start the timer and a method to end it.

一种启动计时器的方法和一种终止计时器的方法。

Once the timer has finished, it will output the total runtime in milliseconds.

计时器结束后,它将以毫秒为单位输出总运行时间。

To start the timer, you use console.time('id for timer') and to end the timer you use console.timeEnd('id for timer') . You can have up to 10,000 timers running simultaneously.

要启动计时器,请使用console.time('id for timer') ,要结束计时器,请使用console.timeEnd('id for timer') 。 您最多可以同时运行10,000个计时器。

The output will look a bit like this timer: 0.57ms

输出看起来像这个timer: 0.57ms

It is very useful when you need to do a quick bit of benchmarking.

当您需要快速进行基准测试时,它非常有用。

结论 (Conclusion)

There we have it, a bit of a deeper look into the console object and some of the other methods that come with it. These methods are great tools to have available when you need to debug code.

我们有了它,对控制台对象及其附带的其他一些方法有了更深入的了解。 这些方法是需要调试代码时可用的出色工具。

There are a couple of methods that I have not talked about as their API is still changing. You can read more about them or the console in general on the MDN Web API page and its living spec page.

由于它们的API仍在更改,因此我没有谈论过几种方法。 您可以在MDN Web API页面及其实时规格页面上了解有关它们或控制台的更多信息。

翻译自: https://www.freecodecamp.org/news/how-to-get-the-most-out-of-the-javascript-console-b57ca9db3e6d/

javascript控制台

javascript控制台_如何充分利用JavaScript控制台相关推荐

  1. javascript排序_鸡尾酒在JavaScript中排序

    javascript排序 Just want the code? Scroll all the way down for two versions of the code: 只需要代码? 一直向下滚动 ...

  2. java chrome 控制台_[Java教程]Chrome 控制台指南

    [Java教程]Chrome 控制台指南 0 2014-09-16 20:01:07 转自:http://blog.jobbole.com/76985/ Chrome的开发者工具已经强大到没朋友的地步 ...

  3. javascript控制台_如何使用JavaScript控制台改善工作流程

    javascript控制台 by Riccardo Canella 里卡多·卡内拉(Riccardo Canella) 如何使用JavaScript控制台改善工作流程 (How you can imp ...

  4. javascript调试_如何提高JavaScript调试技能

    javascript调试 Almost all software developers who have written even a few lines of code for the Web ha ...

  5. javascript学习_真正学习javascript

    javascript学习 So, you think you know JavaScript. You can write conditional statements galore, have ma ...

  6. javascript指南_熟练掌握JavaScript的指南

    javascript指南 So you're trying to learn JavaScript but are inundated with all the different syntax an ...

  7. javascript排序_鸡尾酒用javascript排序

    javascript排序 Just want the code? Scroll all the way down for two versions of the code: 只需要代码? 一直向下滚动 ...

  8. javascript知识点_一点点JavaScript知识是第1部分很危险的事情

    javascript知识点 几乎是一个数据库的奇怪故事 (The Strange Tale of the Almost-a-Database) 这不是教程,这是一个警告性的故事. (This is n ...

  9. javascript案例_如何在JavaScript中使用增强现实-一个案例研究

    javascript案例 by Apurav Chauhan 通过Apurav Chauhan 如何在JavaScript中使用增强现实-一个案例研究 (How to use Augmented Re ...

最新文章

  1. java反序列化 exp_java反序列化-ysoserial-调试分析总结篇(4)
  2. iOS限定UITextField的输入格式
  3. mysql线程异常中断事务_清理MySQL死锁事务线程
  4. quartus总线怎样连接(例如,怎么和ROM连接)
  5. NOIP2005普及组第3题 采药 (背包问题)
  6. 网络知识:DNS 访问原理详解
  7. WPF 获得文件夹路径 FolderBrowserDialog
  8. php 上传apk包到cdn_网站cdn加速,cdn防御系统
  9. 整合Activiti Modeler到业务系统(或BPM平台)
  10. CSS控制div宽度最大宽度/高度和最小宽度/高度
  11. [POI2009]石子游戏Kam
  12. Windows编程系列(前言)
  13. 龙蜥社区8问,你关心的问题都在这里
  14. 简易安装Matlab R2014a 破解版
  15. JAVA数据库连接池的工作机制
  16. windows设置自动获取IP地址
  17. java编程详解 pdf_Java高并发编程详解:多线程与架构设计 高清pdf扫描版[154MB]
  18. Canvas Api(全)
  19. 手机通话记录重复显示怎么处理_华为出现重复联系人 - 卡饭网
  20. 中科院计算机所博士何飞,2017年中科院计算所博士生招生考试说明

热门文章

  1. 面试字节跳动Android工程师该怎么准备?深度解析,值得收藏
  2. php数据接口api安全,API接口数据安全之授权码sign
  3. java---Listener Filter知识点学习
  4. EF ++属性会更新实体
  5. TensorFlow MNIST 入门 代码
  6. 使用Maven创建Web项目后,jsp引入静态文件提示报错。JSP 报错:javax.servlet.ServletException cannot be resolved to a type...
  7. HTML 页面源代码布局介绍
  8. Java 注解 拦截器
  9. ELK学习记录三 :elasticsearch、logstash及kibana的安装与配置(windows)
  10. mysql 表锁——读锁和写锁