console object

console Object represents the JavaScript Console . Although it's not the standard yet , But all major browsers have native support , Has become the de facto standard .

console Objects have two main functions :

  • Display the error message when the web code is running .

  • Provides a command line interface , Used to interact with web code .

console There are many ways to interface to objects , Available for developers to call .


log Method is used in console Window display information .

If the parameter is a normal string ,log Method to display the string content in console window .

console.log("Hello World")
// Hello World console.log("a","b","c")
// a b c

If the parameter is a format string ( Format placeholders are used ),log Method to replace the placeholder with the following , Displayed in the console window .

console.log(" %s + %s = %s", 1, 1, 2)
// 1 + 1 = 2

Code above %s A placeholder for a string , Others are

  • %d, %i Integers
  • %f Floating point numbers
  • %o Links to objects
  • %c CSS Format string

log Method , Can be used in combination with .

console.log(" %s + %s ", 1, 1, "= 2")
// 1 + 1 = 2

console All methods of object , Can be covered . therefore , According to your own needs , Definition console.log Method .

["log", "warn", "error"].forEach(function(method) {
console[method] = console[method].bind(
new Date().toISOString()
}); console.log(" Something went wrong !");
// 2014-05-18T09:00.000Z Something went wrong !

The code above indicates , Use custom console.log Method , You can add the current time in the display results .


except log,console Object also has four ways to output information :

  • debug: Equate to log.

  • info: Equate to log.

  • warn: When outputting information , Add a yellow triangle to the front , A warning .

  • error: When outputting information , Add a red fork at the front , It means that something has gone wrong .

The usage of these four methods is related to log Exactly the same as .

console.error("Error: %s (%i)", "Server is not responding",500)
// Error: Server is not responding (500) console.warn('Warning! Too few nodes (%d)', document.childNodes.length)
// Warning! Too few nodes (1)


For some composite types of data ,console.table Method can be converted to table display .

var languages = [
{ name: "JavaScript", fileExtension: ".js" },
{ name: "TypeScript", fileExtension: ".ts" },
{ name: "CoffeeScript", fileExtension: ".coffee" }
]; console.table(languages);

Code above language, It turns into a table as shown below .

(index) name fileExtension
0 "JavaScript" ".js"
1 "TypeScript" ".ts"
2 "CoffeeScript" ".coffee"

The conditions for composite data to be displayed in tables are , You have to have a primary key . For the array above , A primary key is a number key . For objects , The primary key is its outermost key .

var languages = {
csharp: { name: "C#", paradigm: "object-oriented" },
fsharp: { name: "F#", paradigm: "functional" }
}; console.table(languages);

Code above language, It turns into a table as shown below .

(index) name paradigm
csharp "C#" "object-oriented"
fsharp "F#" "functional"


assert Method is used to verify whether a condition is true . If it is false , A pre specified error message is displayed . The format is as follows .

console.assert( conditional , Output information )

How to use it is as follows .

console.assert(true === false," The judgment is not true ")
// Assertion failed: The judgment is not true

Here's another example , Judge whether the number of child nodes is greater than or equal to 500.

console.assert(list.childNodes.length < 500, " The number of nodes is greater than or equal to 500")


These two methods are used for timing , You can calculate the exact time that an operation takes .

console.time("Array initialize");
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
array[i] = new Object();
}; console.timeEnd("Array initialize"); // Array initialize: 1914.481ms

time Method indicates that the timing starts ,timeEnd Method indicates the end of the time . Their parameter is the name of the timer . call timeEnd After method ,console The window will show “ Timer name : Time spent ”.,console.groupend()

These two methods are used to group the displayed information . It's only useful when you're outputting a lot of information , Information in a group , It can be folded with the mouse / an .

Other methods

  • console.dir(): Output object information , Used to display all the properties of an object .

  • console.clear(): Yes console Clear the window , The cursor returns to the first line .

  • console.trace(): The call path of the currently executed code in the stack .

Command line API

In the console , Besides using console object , You can also use some command line methods that come with the console .

**(1)$_ **

$_ Property returns the value of the previous expression .

// 4
// 4

**(2)$0 - $4 **

The console holds the latest 5 It's in Elements Panel selected DOM Elements ,$0 For the last one ,$1 For the second from the bottom , And so on until $4.

**(3)$(selector) **

$(selector) Returns an array , Include specific CSS All the selectors that match DOM Elements . The method is actually document.querySelectorAll Method alias .

var images = $('img');
for (each in images) {

The above code prints out all the img Elemental src attribute .

**(4)$x(path) **

$x(path) Method returns an array , Contains matching specific XPath All of the expressions DOM Elements .


The above code returns all the information that contains a Elemental p Elements .

**(5)inspect(object) **

inspect(object) Method to open the related panel , And select the corresponding element :DOM The elements are in Elements The panel shows ,JavaScript The object is Profiles It shows that .

**(6)getEventListeners(object) **

getEventListeners(object) Method returns an object , The members of the object register various events of the callback function ( such as click or keydown), Each event corresponds to an array , The members of the array are the callback functions for the event .

**(7)keys(object),values(object) **

keys(object) Method returns an array , Contains all key names for a specific object .

values(object) Method returns an array , Contains all key values for a specific object .

var o = {'p1':'a', 'p2':'b'};
// ["p1", "p2"]
// ["a", "b"]

(8)monitorEvents(object[, events]) ,unmonitorEvents(object[, events])

monitorEvents(object[, events]) Method to listen for specific events on a specific object . When that happens , Will return a Event object , Contains information about the event .unmonitorEvents Method is used to stop listening .

monitorEvents(window, "resize");
monitorEvents(window, ["resize", "scroll"])

The above code represents the listening method of single event and multiple events respectively .

monitorEvents($0, "mouse");
unmonitorEvents($0, "mousemove");

The above code shows how to stop listening .

monitorEvents Allow listening to events of the same class . All events can be divided into four broad categories .

  • mouse:"mousedown", "mouseup", "click", "dblclick", "mousemove", "mouseover", "mouseout", "mousewheel"
  • key:"keydown", "keyup", "keypress", "textInput"
  • touch:"touchstart", "touchmove", "touchend", "touchcancel"
  • control:"resize", "scroll", "zoom", "focus", "blur", "select", "change", "submit", "reset"
monitorEvents($("#msg"), "key");

The above code means to listen to all key A big category of events .

**(9)profile([name]),profileEnd() **

profile Method is used to start a named CPU Performance testing ,profileEnd Method is used to end the performance test .

profile("My profile")
profileEnd("My profile")

**(10) Other methods **

Command line API The following methods are also provided .

  • clear() Method to clear the history of the console .
  • copy(object) Method to copy a specific DOM Elements to the clipboard .
  • dir(object) Method to display all properties of a specific object , yes console.dir Method alias .
  • dirxml(object) Method to display the XML form , yes console.dirxml Method alias .

debugger sentence

debugger Statement must be used with debugging tools , If there is no debugging tool ,debugger Statement does not produce any results .

stay chrome Browser , When the code runs to debugger The specified line , It will stop running , Turn on automatically console Interface . It works like setting breakpoints .

for(var i = 0;i<5;i++){
if (i===2) debugger;

The above code prints out 0,1,2 in the future , It will be suspended , Turn on automatically console window , Waiting for further processing .


Browser console console More articles about

  1. Browser console console Use

    In the team project the day before yesterday, due to the product requirements, the data of multiple pages is needed as the parameters of the submission interface when submitting the order , The need is intoxicating , The project with angular To do the , There's no way. You can only use global variables to define the values and localStorage The coming ...

  2. chrome Browser console console The solution to the problem of not printing information

    Google browser console can't display consle Print stuff , I remember printing normally before , There's no problem with the code , Maybe you accidentally click in the browser fifter, We 2 The simplest and most crude method can be used ----> Restore defaults . Press down F12, ...

  3. chrome Browser console console The solution to the problem of not printing information .

    from : Recently changed the installation chrome, Want to press F12 Debug the code , I found that everything on the console ...

  4. How to use the browser console (console) Output color style debugging information in

    console.log(XX,XX,XX) log  The first parameter of the declaration is the second . The function of the third parameter , The second parameter is style , The third parameter is the string to output console.log("%c%s", ...

  5. console.debug() Browser console printout Just supporting console Print in your browser

    console.debug() Browser console printout Just supporting console Print in your browser var util = {}; /** * Tool class */ util = new function() { /* ...

  6. Independent of browser console JavaScript Breakpoint debugging method

    As browsers become more powerful , In most cases, code debugging can be solved by some debugging tools provided by the browser . However, for some special cases, we still can't enjoy the power of browser Debugging capability , such as QQ Client embedded web Debugging of ( Although I say QQ At present already ...

  7. 1.Google Chrome browser Console full resolution

    Google Chrome browser Console full resolution stay Google Chrome Before the browser comes out , I always use FireFox, because FireFox The plug-ins are very rich , But because of FireFox Have a strong Firebug, about ...

  8. vue How to debug in the browser console Google plug-in vue Devtools

    vue How to debug in the browser console Google plug-in vue Devtools problem : vuejs The variables inside , How to use the browser console see ? for example , Want to be in chrome In the use console.log Check the variable $data, ...

  9. Why the browser console return is not undefined, It's a bunch of numbers

    setTimeout( (function(){console.log("ok")} )(), 16) When you enter this code in the browser console, it doesn't return "undefined&q ...

Random recommendation

  1. Be an armchair strategist : Introduction of sorting algorithm and C Realization

    author :Vamei Source : Welcome to reprint , Please also retain this statement . thank you ! Sorting algorithm (Sorting Algorithm) It's an integral part of computer algorithms . Sort of ...

  2. Solr Brief description of master slave cluster configuration

    About solr The cluster is mainly divided into master-slave and SolrCloud Two kinds of . Master-slave , It's more suitable for reading based scenes .SolrCloud Suitable for large amount of data , There will be updates from time to time . that solr The master-slave configuration of is very simple . stay solrconfig.xml ...

  3. Linux Missing in system GUI Caused by equipment HeadlessException

    The lack of X11 Display settings Exception in thread "AWT-EventQueue-0" java.awt.HeadlessException: No X11 DISPLA ...

  4. UI Chapter —— User experience

    The content is original , Please note the reprint, thank you . User experience (User Experience, abbreviation UX) It's about users (users) And interaction (interactive) The whole concept of technology systems . say concretely , It represents a website ...

  5. use react Refactoring personal websites 3-22

    Question 1 :import React from 'react' What's the matter with this way of writing ? answer :require yes common.js Writing ,import yes ES6 Writing , The main function is to introduce modules , In writing : var mo ...

  6. C# And Compare the two word The content of the document

    utilize Microsoft.Office.Interop.Word Compare components . Introduce namespace :using Word2013 = Microsoft.Office.Interop.Word; The code is as follows : ...

  7. php soapclient Overtime Set up

    use php Of soapclient, The default is 60 second . Can be found in php.ini Internal configuration , restart APache Or in PHP Make settings in the code ini_set('default_socket_timeout', 300);// ...

  8. Apollo2.5 Camera installation

    Preface : stay Apollo Meiyan team and Changsha CiDi With the support of the team , Recently completed Apollo Recommended Cameras AR023ZWDR(Rev663F12) debugging , Right here. Apollo Make a supplement to your notes , I hope future developers don't have to step on me ...

  9. canvas The background is transparent

    theCanvas = document.getElementById('canvasOne');var context = theCanvas.getContext('2d'); ...

  10. bootstrap-table Data table in row modification

    bootstrap-table In line modification of data js Set the properties of the column in editable : { type : 'text',// The data is displayed in a text box emptytext : "--",// ...