Console Object and console

console object

The console object is a native JavaScript object. It is a bit like the standard output stdout and standard error stderr of Unix systems. It can output various information to the console and also provides many useful auxiliary methods.

There are two common uses of console.

-Debug program, display error information when webpage code is running. -Provides a command line interface to interact with webpage code.

The browser implementation of the console object is included in the development tools that come with the browser. Take the "Developer Tools" of the Chrome browser as an example, you can use the following three methods to open it.

  1. Press F12 or Control + Shift + i (PC)/ Command + Option + i (Mac).
  2. Select "Tools/Developer Tools" from the browser menu.
  3. On a page element, open the right-click menu and select "Inspect Element".

After opening the developer tools, there are multiple panels at the top.

-Elements: View the HTML source code and CSS code of the webpage. -Resources: View various resource files loaded on web pages (such as code files, font files, CSS files, etc.), and various content created on the hard disk (such as local cache, Cookie, Local Storage, etc.). -Network: View the HTTP communication status of the web page. -Sources: View the source code of the script loaded by the webpage. -Timeline: View changes in various web page behaviors over time. -Performance: View the performance of the web page, such as CPU and memory consumption. -Console: Used to run JavaScript commands.

These panels have their own purposes. Only the Console panel (also known as the console) will be introduced below.

The Console panel is basically a command line window. You can type various commands at the prompt.

Static methods of console objects

The various static methods provided by the console object are used to interact with the console window.

console.log(), console.info(), console.debug()

The console.log method is used to output information on the console. It can accept one or more parameters and connect them to output.

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

The console.log method will automatically add a newline character at the end of each output.

console.log(1);
console.log(2);
console.log(3);
// 1
// 2
// 3

If the first parameter is a format string (using format placeholders), the console.log method will replace the placeholders with the following parameters in turn, and then output.

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

In the above code, the first parameter of the console.log method has three placeholders (%s), and the second, third, and fourth parameters will replace these three placeholders in sequence when displayed.

The console.log method supports the following placeholders. Different types of data must use corresponding placeholders.

-%s string -%d integer -%i integer -%f floating point number -Link to %o object -%c CSS format string

var number = 11 * 9;
var color = "red";

console.log("%d %s balloons", number, color);
// 99 red balloons

In the above code, the second parameter is a numeric value, and the corresponding placeholder is %d, the third parameter is a string, and the corresponding placeholder is %s.

When using the %c placeholder, the corresponding parameter must be CSS code, which is used for CSS rendering of the output content.

console.log(
  "%cThis text is styled!",
  "color: red; background: yellow; font-size: 24px;"
);

After the above code runs, the output will be displayed as red letters on a yellow background.

The two parameter formats of the console.log method can be used in combination.

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

If the parameter is an object, console.log will display the value of the object.

console.log({ foo: "bar" });
// Object {foo: "bar"}
console.log(Date);
// function Date() {[native code]}

The above code outputs the value of the Date object, and the result is a constructor.

console.info is an alias of the console.log method, and the usage is exactly the same. It's just that the console.info method will add a blue icon in front of the output information.

The console.debug method is similar to the console.log method, and debugging information will be output to the console. However, by default, the information output by console.debug will not be displayed, and will only be displayed when the display level is turned on at verbose.

All methods of the console object can be overridden. Therefore, you can define the console.log method according to your needs.

["log", "info", "warn", "error"].forEach(function (method) {
  console[method] = console[method].bind(console, new Date().toISOString());
});

console.log("Something went wrong!");
// 2014-05-18T09:00.000Z Something went wrong!

The above code indicates that using the custom console.log method, the current time can be added to the displayed result.

console.warn(), console.error()

The warn method and the error method also output information on the console. The difference between them and the log method is that when the warn method outputs information, a yellow triangle is added to the front to indicate a warning; error When the method outputs information, a red cross is added to the front to indicate an error. At the same time, the output text and the stack where the error occurred will be highlighted. All other aspects are the same.

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)

It can be understood that the log method is to write the standard output (stdout), the warn method and the error method are to write the standard error (stderr).

console.table()

For some complex types of data, the console.table method can convert it to a table display.

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

console.table(languages);

The language variable in the above code is converted into a table and shown as follows.

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

The following is an example of displaying the contents of the table.

var languages ​​= {
  csharp: {name: "C#", paradigm: "object-oriented" },
  fsharp: {name: "F#", paradigm: "functional"}
};

console.table(languages);

The language of the above code is converted into a table and shown as follows.

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

console.count()

The count method is used to count and output how many times it has been called.

function greet(user) {
  console.count();
  return "hi " + user;
}

greet("bob");
// : 1
// "hi bob"

greet("alice");
// : 2
// "hi alice"

greet("bob");
//: 3
// "hi bob"

Each time the above code calls the greet function, the internal console.count method outputs the number of executions.

This method can accept a string as a parameter, as a label, to classify the number of executions.

function greet(user) {
  console.count(user);
  return "hi " + user;
}

greet("bob");
// bob: 1
// "hi bob"

greet("alice");
// alice: 1
// "hi alice"

greet("bob");
// bob: 2
// "hi bob"

The above code shows that bob is executed twice and alice is executed once according to the different parameters.

console.dir(), console.dirxml()

The dir method is used to inspect an object and display it in a format that is easy to read and print.

console.log({ f1: "foo", f2: "bar" });
// Object {f1: "foo", f2: "bar"}

console.dir({ f1: "foo", f2: "bar" });
// Object
// f1: "foo"
// f2: "bar"
// __proto__: Object

The above code shows the output of the dir method, which is easier to read and more informative than the log method.

This method is very useful for outputting DOM objects, because all the attributes of the DOM object are displayed.

console.dir(document.body);

In the Node environment, you can also specify the output in the form of code highlighting.

console.dir(obj, { colors: true });

The dirxml method is mainly used to display DOM nodes in the form of a directory tree.

console.dirxml(document.body);

If the parameter is not a DOM node, but a normal JavaScript object, console.dirxml is equivalent to console.dir.

console.dirxml([1, 2, 3]);
// Equivalent to
console.dir([1, 2, 3]);

console.assert()

The console.assert method is mainly used for conditional judgment during program running. If the condition is not met, an error will be displayed, but the program execution will not be interrupted. This is equivalent to prompting the user that the internal state is incorrect.

It accepts two parameters, the first parameter is an expression, and the second parameter is a string. Only when the first parameter is false, an error will be prompted, and the second parameter will be output to the console, otherwise there will be no results.

console.assert(false, "The judgment condition is not established");
// Assertion failed: The judgment condition is not established

// equivalent to
try {
  if (!false) {
    throw new Error("The judgment condition is not established");
  }
} catch (e) {
  console.error(e);
}

The following is an example to determine 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"
);

In the above code, if the number of eligible nodes is less than 500, there will be no output; only when it is greater than or equal to 500, an error will be prompted on the console and the specified text will be displayed.

console.time(), console.timeEnd()

These two methods are used for timing and can calculate the exact time spent in an operation.

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

The time method indicates the start of timing, and the timeEnd method indicates the end of timing. Their parameter is the name of the timer. After calling the timeEnd method, the console will display "Timer name: Elapsed time".

console.group(), console.groupEnd(), console.groupCollapsed()

The two methods console.group and console.groupEnd are used to group the displayed information. It is only useful when outputting a large amount of information. The information grouped in a group can be folded/expanded with the mouse.

console.group("First level group");
console.log("The content of the first level group");

console.group("Secondary group");
console.log("The content of the secondary group");

console.groupEnd(); // End of secondary group
console.groupEnd(); // End of first level grouping

The above code will display the "secondary grouping" inside the "first-level grouping", and there is a folding symbol in front of the "first-level grouping" and "secondary grouping", which can be used to fold the content of this level.

The console.groupCollapsed method is very similar to the console.group method. The only difference is that the content of the group is collapsed instead of expanded when it is first displayed.

console.groupCollapsed("Fetching Data");

console.log("Request Sent");
console.error("Error: Server not responding (500)");

console.groupEnd();

The above code only displays one line of "Fetching Data", which will only be expanded when clicked, and the two lines contained in it will be displayed.

console.trace(), console.clear()

The console.trace method displays the call path of the currently executing code in the stack.

console.trace();
// console.trace()
// (anonymous function)
// InjectedScript._evaluateOn
// InjectedScript._evaluateAndWrap
// InjectedScript.evaluate

The console.clear method is used to clear all the output of the current console and return the cursor to the first line. If the user selects the "Preserve log" option of the console, the console.clear method will not work.

Console command line API

In the browser console, in addition to using the console object, you can also use some of the command line methods that come with the console.

(1) $_

The $_ attribute returns the value of the previous expression.

2 + 2;
// 4
$_;
// 4

(2) $0-$4

The console saves the last 5 DOM elements selected in the Elements panel, $0 represents the first (most recent) from the bottom, $1 represents the second from the bottom, and so on until $4.

(3) $(selector)

$(selector) returns the first matched element, which is equivalent to document.querySelector(). Note that if the page script has a definition for $, it will overwrite the original definition. For example, if there is jQuery in the page, the execution of $(selector) in the console will adopt the implementation of jQuery and return an array.

(4) $$(selector)

$$(selector) returns the selected DOM object, which is equivalent to document.querySelectorAll.

(5) $x(path)

The $x(path) method returns an array containing all DOM elements that match a specific XPath expression.

$x("//p[a]");

The above code returns all p elements that contain a elements.

(6) inspect(object)

The inspect(object) method opens the relevant panel and selects the corresponding element to display its details. DOM elements are displayed in the Elements panel, for example, inspect(document) will display the document element in the Elements panel. JavaScript objects are displayed in the console panel Profiles panel, such as inspect(window).

(7) getEventListeners(object)

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

(8) keys(object), values(object)

The keys(object) method returns an array containing all the keys of object.

The values(object) method returns an array containing all the key values ​​of object.

var o = { p1: "a", p2: "b" };

keys(o);
// ["p1", "p2"]
values(o);
// ["a", "b"]

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

The monitorEvents(object[, events]) method monitors specific events that occur on specific objects. When an event occurs, an Event object is returned, which contains information about the event. The unmonitorEvents method is used to stop monitoring.

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

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

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

The above code shows how to stop monitoring.

monitorEvents allows to monitor events of the same category. All events can be divided into four major 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 monitor all events of the key category.

(10) Other methods

The command line API also provides the following methods.

-clear(): Clear the history of the console. -copy(object): Copy a specific DOM element to the clipboard. -dir(object): displays all the attributes of a specific object. It is an alias of the console.dir method. -dirxml(object): Displays the XML format of a specific object. It is an alias of the console.dirxml method.

debugger statement

The debugger statement is mainly used for debugging and is used to set breakpoints. If there is a debugging tool running, the program will automatically stop when it reaches the debugger statement. If there is no debugging tool, the debugger statement will not produce any results, and the JavaScript engine will automatically skip this sentence.

In the Chrome browser, when the code runs to the debugger statement, it will pause and automatically open the script source code interface.

for (var i = 0; i < 5; i++) {
  console.log(i);
  if (i === 2) debugger;
}

After the above code prints 0, 1, and 2, it will pause, automatically open the source code interface, and wait for further processing.