The console should be indispensable to most front-end developers in their daily development and debugging. However, the console still has a lot of unknown properties and methods to make it more enjoyable to use, including some hidden pits (console.log object print bug #feature)… * This article discusses the console in Chrome development tools, other browsers may have different performance, this article does not deal with * object printing problems at the end of the article click jump
Try it first!
Before we start, let’s make a Mario! Open the developer tools console, copy and paste the following code, and hit Enter!
! (navigator.userAgent.toLowerCase().indexOf('chrome') > - 1)?null : (function() {
var args = [], eightBitHack = [], coordinates = ["41n8r2"."42t3wu"."449u8a"."4h4014"."4h2c4y"."4g6ia1"."4286dm"."447r6w"."4fudcv"."61z2xp"."70rmyd"."71sfq1"."6zgplp"."42spfv"."4frvnp"."61wzpd"];
for (var row = coordinates.length; row--;) {
var decompressedRow = parseInt(coordinates[row], 36).toString(5).split(' ');
coordinates[row] = decompressedRow.splice(1, decompressedRow.length- 1);
for (var cell = coordinates[row].length; cell--;) {
var dot = parseInt(coordinates[row][cell]);
var color = dot === 4 ? '#ecd585' : dot === 3 ? '#e1c25b' : dot === 2 ? '# 805936' : dot ? '#ec2733' : '#fff';
args.unshift("border: 8px solid color;".replace('color', color));
eightBitHack.unshift("%c");
}
eightBitHack.unshift("\n");
}
eightBitHack.push("%c\n\n\n"."\nIt's me, Mario!"."\nmade by %chttps://twitter.com/aristretto");
args.push("font-weight: bold;"."font-weight: bold; color: teal;");
args.unshift(eightBitHack.join(' '));
console.log.apply(console, args); }) ();Copy the code
A colorful Mario appears on the console
Console. log(‘%c’,’/* CSS */’);
* Of course, there are other trick processing methods, please see detailsThe authors link
Console advanced gameplay
As you can see from the examples above, there are a lot of gameplay advancements that we don’t know about on the console, such as better formats for output, and some tricks to make debugging more efficient.
Console API
Enter console. As you can see, there are many methods to call console. There are many resources available on the web
console.log(object[,object,…] )
Console. log has the following uses besides passing the output directly to the first parameter:
- If you pass in multiple parameters, each comma will be automatically replaced with a space
console.log('Hello'.'world! \t'.'Current Time:'.Date.now());
// Hello world! Current Time: 1530694211342
Copy the code
- Output using specifiers, similar to C++
print
function
In addition to the general%s
(String),%i``%d
(all integers),%f
Outside, also support%c
(Style),%o
(DOM element),%O
(JavaScript object) output
console.log('Hello world! \t%s: %i'.'Current Time'.Date.now());
console.log("normal text,%c large blue text,%c white text with black background "."color: blue; font-size: x-large"."color:white; background:black;");
console.log('%o\n%O'.document, {a:1.b:2.c:3});
Copy the code
The output of the above code is shown below:
console.count
Write the number of times count() is called on the same line with the same label, which can be used for certain setintervals or for debugging triggered repeatedly by events.
const fn = function(name){
console.count(name);
};
fn('Bob'); // Bob: 1
fn('John'); // John: 1
fn('Bob'); // Bob: 2
fn('Bob'); // Bob: 3
Copy the code
console.error console.trace
Output a message with stack information for where the method was called. The difference is that error sets the message to the wrong style.
((a)= >{
const fn1 = (fn) = >{
fn();
};
const fn2 = (a)= >{
console.trace('Target Not Found');
console.error('Target Not Found'); }; fn1(fn2); }) ();Copy the code
The output of the above code is shown below:
console.time timeEnd
Start a new timer with associated labels. When console.timeend () is called with the same label, the timer stops and the elapsed time is displayed in the console. Timer values are accurate to submillisecond. The strings passed to time() and timeEnd() must match or the timer will not end. Can be used to analyze the time consumption of a piece of code.
console.time('test');
for(let i = 0; i < 100000000; i++){}
console.timeEnd('test');
/ / output:
/ / test: 122.71923828125 ms
Copy the code
Others
In addition, there are many useful Console apis, such as console.table, console.group, console.assert, and so on. You can find their use in Chrome’s Console API documentation.
Command Line API
Try typing $,? In the console of a page without jQuery and Zepto. What happens?
// Enter directly from the console
console.log($,?) ;/ / output:
ƒ $(selector, [startNode]) {[Command Line API]} ƒ? (selector, [startNode]) { [Command Line API] }
Copy the code
As you can see, the output function contains [Command Line API]. The Command Line API is a collection of convenient functions provided by the console to select and examine DOM elements, display data in a readable format, stop and start parsers, and monitor DOM events. * Note 1: This type of API is only available from the console itself, including this type of code in the JS code will report an error. * Note 2: Methods with the same name will be overridden if they are overridden globally.
$、?
$(the selector) is equivalent to the document. QuerySelector, likewise, $(selector) is equal to the document. QuerySelectorAll. The Command Line API simply provides a quick way for developers to debug.
$0 – $4
The $0, $1, $2, $3, and $4 commands are used as a historical reference for the last five DOM Elements checked in the Elements panel or the last five JavaScript heap objects selected in the Profiles panel. $0 returns the most recently selected element or JavaScript object, $1 returns the most recently selected element or object, and so on. The following result is the result of clicking the HTML tag, head tag, and Meta tag in sequence on the test page:
others
In addition, there are many useful Command Line apis such as Copy, Debug, Monitor, profile, and so on. You can find their use in Chrome’s Command Line API documentation.
Console pit
Consider the following output from the console:
const fn = function(length){
const o = {
arr: [].key1: 'test'.key2: 'test'.key3: 'test'.key4: 'test'.key5: 'test'.index: 0
};
console.log(JSON.stringify(o));
console.log(o);
console.log('Handling data');
for(let i = 0; i < length; i++){
o.arr.push(i);
}
o.index = length;
console.log(JSON.stringify(o));
console.log(o);
};
fn(5);
Copy the code
As you can see, the output from the console should look like this:
At this point, if we expand the second and fifth lines, we will find a very strange phenomenon:
Delay calculation problem
To locate the problem, simply hover the mouse over the blue INFO tag at the end of the line and the console will prompt the following: Value below was evaluated just now. In order to show the key-value of the current object, the control console will calculate the key-value of the object. When the Console is used for printing, if it finds that the current content to be printed is an object, the Console saves it and outputs a Snapshot. When the developer needs to view the detailed content, click expand to return the value in memory. This is a known pit in the console, and it is possible that this feature was designed to prevent the console from copying output from large objects, which would lead to slow debugging, or to make it easier to see properties on the prototype chain, but this is definitely something developers need to avoid when debugging code. To avoid this debugging problem, it is recommended to use json.stringify () for output debugging rather than printing the current object directly.
Memory leak problem
As mentioned above, when you print an object using Console, a reference to that object is saved. Because the developer tools are enabled by default in the browser and the “developer will need to see this object later” behavior is default, objects introduced in the Console do not make it into the GC logic, which causes memory leaks. Memory leaks can be avoided by separating the development environment from the online environment, where console-printed statements are avoided, or by turning no-console on in ESLint when the project is packaged.
Reference and Extension
medium.com/@aristretto… Developers.google.com/web/tools/c… Stackoverflow.com/questions/1…