javascript控制臺_如何充分利用JavaScript控制臺

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控制臺

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395747.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395747.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395747.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Django之靜態文件配置

靜態文件 了解靜態文件配置之前,我們需要知道靜態文件是什么? 靜態文件其實指的是像css,js,img等一些被模板需要的文件。 如何在Django中配置我們的靜態文件 1.建立static文件夾,將靜態文件放在該目錄下 2.在settings文件下配置如…

神奇的圖像處理算法

http://blog.chinaunix.net/uid-23065002-id-4392043.html http://blog.csdn.net/k_shmily/article/details/51138154 幾周前,我介紹了相似圖片搜索。 這是利用數學算法,進行高難度圖像處理的一個例子。事實上,圖像處理的數學算法&#xff0c…

JavaWeb項目前端規范(采用命名空間使js深度解耦合)

沒有規矩不成方圓,一個優秀的代碼架構不僅易于開發和維護,而且是一門管理與執行的藝術。 這幾年來經歷了很多項目,對代碼之間的強耦合及書寫不規范,維護性差等問題深惡痛絕。在這里,通過仔細分析后,結合自己…

java重要基礎知識點_java基礎知識點整理

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓java基礎知識點整理1.&和&&的區別?&:邏輯與(and),運算符兩邊的表達式均為true時,整個結果才為true。&&:短路與,如果第一個表達式為false時&#…

網易云音樂的算法有什么特點_當算法設計音樂廳時會發生什么?

網易云音樂的算法有什么特點Here are three links worth your time:這是三個值得您花費時間的鏈接: What happens when algorithms design a concert hall? (3 minute read) 當算法設計音樂廳時會發生什么? ( 閱讀3分鐘 ) How to land a top-notch tec…

開機發現超級管理員賬戶不見了

今天出現了一個怪現象,連接打印機的電腦上沒有超級管理員賬戶,只有一個剛建立的新賬戶,這是怎們回事來?噯,原來啊,安裝Windows XP時,如果又設置了一個管理員賬戶,那么系統內置沒有密…

vs自帶iis局域網調試

http://www.cnblogs.com/liluping860122/p/4685564.html轉載于:https://www.cnblogs.com/wcLT/p/5594252.html

java.util.set cannot be assigned from null_Java中有關Null的9件事

對于Java程序員來說,null是令人頭痛的東西。時常會受到空指針異常(NPE)的騷擾。連Java的發明者都承認這是他的一項巨大失誤。Java為什么要保留null呢?null出現有一段時間了,并且我認為Java發明者知道null與它解決的問題相比帶來了更多的麻煩&…

node.js事件驅動_了解Node.js事件驅動架構

node.js事件驅動by Samer Buna通過Samer Buna 了解Node.js事件驅動架構 (Understanding Node.js Event-Driven Architecture) Update: This article is now part of my book “Node.js Beyond The Basics”.更新:這篇文章現在是我的書《超越基礎的Node.js》的一部分…

如何基于 Notadd 構建 API (Laravel 寫 API)

如何基于 Notadd 構建 API Notadd 底層實現了 passport 機制,有統一的授權管理,主要支持兩種方式進行 API 授權,一個是 client,領一個是 passport,這個在其他文檔中有做詳細的說明。 這里主要說的是,如何基…

mysql 基于集_一種基于記錄集查找特定行的方法_MySQL

問:我的一個表中包含了名為IdValue的單列主鍵。對于給定的IdValue值,我希望找到緊鄰目標值之前和之后的表行(假定結果按IdValue排序)。怎樣才能不使用游標而通過一個基于集合的方法得到需要的結果?答:Transact-SQL是一個基于集合的…

react 交互_如何在React中建立動畫微交互

react 交互Microinteractions guide a user through your application. They reinforce your user experience and provide delight.微交互引導用戶完成您的應用程序。 它們可以增強您的用戶體驗并帶來愉悅感。 You may have seen some of the slick examples of microinterac…

HTTPS與MITM

HTTPS:基于SSL/TSL的HTTP協議 MITM:Man-In-The-Middle中間人攻擊 Https下中間人攻擊的思路: 1 去https化 2 向CA申請相似域名的證書 防范: 睜大雙眼轉載于:https://www.cnblogs.com/the-owl/p/5596254.html

PCB genesis自制孔點 Font字體實現方法

一.先看genesis原有Font字體 在PCB工程CAM加孔點字體要求時,通常我們直接用Geneis軟件給我們提供了2種孔點字體canned_57與canned_67,但此字體可能不能滿足各個工廠個性化需求,比如:孔密度,孔間距,孔形狀分布,如果有一…

Google 最新的 Fuchsia OS【科技訊息摘要】

轉自:http://www.cnblogs.com/pied/p/5771782.html 就是看到篇報道,有點好奇,就去FQ挖了點東西回來。 我似乎已開始就抓到了重點,沒錯,就是 LK 。 LK 是 Travis Geiselbrecht 寫的一個針對 ARM 的嵌入式操作系統&#…

java 03_Java基礎03—流程控制

流程控制參考資料:《Java從入門到精通》/明日科技編著. 4版. 北京:清華大學出版社,2016一、復合語句Java的復合語句由“{”開始,“}”結束,又稱為塊語句。復合語句都是由上至下被執行;復合語句中可以嵌套復…

這三種策略可以幫助女性在科技領域蓬勃發展

by Shubhi Asthana通過Shubhi Asthana 這三種策略可以幫助女性在科技領域蓬勃發展 (These 3 strategies can help women thrive in tech) As someone early on in her career, I’ve attended a few tech talks, conferences, and meetups. One thing I noticed is not many w…

手機衛士09_應用程序四種查看_ListView小標題_進程管理

手機衛士09_應用程序四種查看_ListView小標題_進程管理 1.懸浮窗體的功能實現: 1.1.應用程序的卸載: 包安裝器 packageInstall,包卸載packageruninstall intent.setData(Uri.pare(“package:” 應用程序包名)) 卸載完之后記得更新list集合,更新適配器. 但是不確定用戶是否點了…

pandas:根據行間差值進行數據合并

1. 問題描述 在處理用戶上網數據時,用戶的上網行為數據之間存在時間間隔,按照實際情況,若時間間隔小于閾值(next_access_time_app),則可把這幾條上網行為合并為一條行為數據;若時間間隔大于閾值…

Flask學習 一 基本結構

-from flask import Flaskfrom flask import Flask,render_template-from flask import request-from flask import make_response-from flask import abort-from flask import redirect-# __name__參數決定程序的根目錄app Flask (__name__)-# app.route (/)-# def hello_wor…