Translator: Front-end wisdom

Original text: medium.com/@mattburges… Medium.freecodecamp.org/10-tips-to-…

The more you know, the more you don’t know

Like it and see. Make it a habit


GitHub: github.com/qq449245884… Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.

The most common height for Web development is console.log, and while console.log has its place, many people don’t realize that console itself has many more methods than the basic log method. Appropriate use of these methods can make debugging easier, faster, and more intuitive.

console.log()

There are a lot of features in console.log that people don’t expect. While most people use console.log(object) to view objects, you can also use console.log(object, otherObject, String), which keeps them all neatly recorded and occasionally comes in handy.

Not only that, but there’s another format: console.log(MSG, values), which is a lot like sprintf in C or PHP.

console.log('I like %s but I do not like %s.', 'Skittles', 'pus');
Copy the code

It will output as you would expect:

> I like Skittles but I do not like pus.
Copy the code

The common placeholder %o (this is the letter O, not 0) accepts objects, %s accepts strings, and %d represents decimals or integers.

Another interesting thing is %c, which, contrary to what you might think, is actually a placeholder for CSS values. When using the %c placeholder, the corresponding subsequent argument must be a CSS statement used to render the output with CSS. There are two common output methods: text style, image output.

console.log('I am a %cbutton', 'color: white; background-color: orange; padding: 2px 5px; border-radius: 2px');
Copy the code

It’s not elegant, and it’s not particularly useful. Of course, this isn’t really a button.

Does it work? Boon boon boon.

console.dir()

In most cases, console.dir() ‘s function is very similar to log(), although it looks slightly different.

The small drop-down arrow displays the same object details as above, which can also be seen in the console.log version. When you look at the structure of the elements, the differences between them are much larger and more interesting.

let element = document.getElementById('2x-container');
Copy the code

Use console.log to view:

Some elements open, which clearly shows the DOM and allows us to navigate through it. But console.dir(element) gives a more convenient output for viewing the DOM structure:

This is a more objective way of looking at elements. Sometimes, this might be what you really want, more like checking elements.

console.warn()

Probably the most obvious direct replacement for log(), you can use console.warn() in exactly the same way. The only real difference is that the color of the output word is yellow. Specifically, the output is at the warning level rather than the information level, so the browser treats it a little differently. This has the effect of making it more visible in cluttered output.

However, there is an even bigger advantage because the output is a warning rather than a message, so you can filter out all console. logs and keep only console.warn. This is especially useful for applications that occasionally output a lot of useless crap in the browser. Clearing out some useless information makes it easier to see the output you want.

console.table()

Surprisingly, this is less well known, but the console.table() function aims to display table data in a cleaner way than just rolling out the original object array.

For example, here is a list of data.

const data = [{
  id: "7cb1-e041b126-f3b8",
  seller: "WAL0412",
  buyer: "WAL3023",
  price: 203450,
  time: 1539688433
},
{
  id: "1d4c-31f8f14b-1571",
  seller: "WAL0452",
  buyer: "WAL3023",
  price: 348299,
  time: 1539688433
},
{
  id: "b12c-b3adf58f-809f",
  seller: "WAL0012",
  buyer: "WAL2025",
  price: 59240,
  time: 1539688433
}];
Copy the code

If we used console.log to output the above, we would get some pretty useless output:

▶ (3) [{...}, {...}, {...}]Copy the code

Clicking on this little arrow expands the contents of the object, but it’s not as “at a glance” as we want.

But the output from console.table(data) is much more useful.

The second optional argument is the list of required columns. Obviously, all columns are defaults, but we could also do this:

> console.table(data, ["id", "price"]);
Copy the code

Note here that this is out of order – the arrow on the rightmost column header shows why. I click on the column to sort. Finding the maximum or minimum of a column, or just looking at the data differently, is handy. Incidentally, this feature has nothing to do with just displaying a few columns; it’s always available.

Console.table () can only handle a maximum of 1000 rows, so it may not fit all datasets.

console.assert()

Assert () is the same function as log(). Assert () asserts an input expression and only prints information to the console if the expression is false, as shown in the following example:

var arr = [1, 2, 3];
console.assert(arr.length === 4);
Copy the code

Sometimes we need more complex conditional sentences. For example, we’ve seen data problems with user WAL0412 and want to display only transactions from that data, which is a straightforward solution.

console.assert(tx.buyer === 'WAL0412', tx);
Copy the code

It looks good, but it won’t work. Remember that the condition must be false for the assertion to be executed, with the following change:

console.assert(tx.buyer ! == 'WAL0412', tx);Copy the code

Like some of these, console.assert() is not always particularly useful. But in certain situations, it can be an elegant solution.

console.count()

Another special purpose counter, count, is just a counter, or a named counter, that counts the number of times code is executed.

for(let i = 0; i < 10000; i++) {
  if(i % 2) {
    console.count('odds');
  }
  if(!(i % 5)) {
    console.count('multiplesOfFive');
  }
  if(isPrime(i)) {
    console.count('prime');
  }
}
Copy the code

This isn’t useful code, and it’s a little abstract. I’m not going to do isPrime here, assuming it’s true.

After executing, we get a list:

odds: 1
odds: 2
prime: 1
odds: 3
multiplesOfFive: 1
prime: 2
odds: 4
prime: 3
odds: 5
multiplesOfFive: 2
...
Copy the code

There is also a related console.countreset () that you can use to reset the counter.

console.trace()

Trace () is difficult to demonstrate in simple data. Its advantages come into play when you try to figure out in a class or library which actual caller is causing the problem.

For example, you might have 12 different components calling a service, but one of them doesn’t set its dependencies correctly.

export default class CupcakeService { constructor(dataLib) { this.dataLib = dataLib; if(typeof dataLib ! == 'object') { console.log(dataLib); console.trace(); }}... }Copy the code

Console.log () only tells us what the dataLib is, not where it was passed. However, console.trace() makes it very clear that the problem is dashboard.js, and we can see that new CupcakeService(false) is causing the error.

console.time()

Console.time () is a special function for tracking operation times, which is a great way to track JavaScript execution times.

function slowFunction(number) {
  var functionTimerStart = new Date().getTime();
  // something slow or complex with the numbers. 
  // Factorials, or whatever.
  var functionTime = new Date().getTime() - functionTimerStart;
  console.log(`Function time: ${ functionTime }`);
}
var start = new Date().getTime();

for (i = 0; i < 100000; ++i) {
  slowFunction(i);
}

var time = new Date().getTime() - start;
console.log(`Execution time: ${ time }`);
Copy the code

This is old-school, and we use console.time() to simplify the code above.

const slowFunction = number =>  {
  console.time('slowFunction');
  // something slow or complex with the numbers. 
  // Factorials, or whatever.
  console.timeEnd('slowFunction');
}
console.time();

for (i = 0; i < 100000; ++i) {
  slowFunction(i);
}
console.timeEnd();
Copy the code

We no longer need to do any calculations or set temporary variables.

console.group()

// this is the global scope
let number = 1;
console.group('OutsideLoop');
console.log(number);
console.group('Loop');
for (let i = 0; i < 5; i++) {
  number = i + number;
  console.log(number);
}
console.groupEnd();
console.log(number);
console.groupEnd();
console.log('All done now');
Copy the code

The output is as follows:

Not very useful, but you can see how some of them are combined.

class MyClass {
  constructor(dataAccess) {
    console.group('Constructor');
    console.log('Constructor executed');
    console.assert(typeof dataAccess === 'object', 
      'Potentially incorrect dataAccess object');
    this.initializeEvents();
    console.groupEnd();
  }
  initializeEvents() {
    console.group('events');
    console.log('Initialising events');
    console.groupEnd();
  }
}
let myClass = new MyClass(false);
Copy the code

Select the DOM element

If you are familiar with jQuery, you know how important the $(‘. Class ‘) and $(‘#id’) selectors are. They select DOM elements based on the class or ID they are associated with.

But when you’re not referencing jQuery, you can still do the same thing in the Google Development console.

$(‘tagName’) $(‘.class’) $(‘#id’) and $(‘.class #id’) are equivalent to Document.querySelector (‘ “), which returns the first element in the DOM that matches the selector.

Can be used? (tagName) or? (.class), note the binary notation, and select all elements of the DOM according to a specific selector. This also puts them into the array, and you can also select specific elements from the array by specifying the location of that element.

For example,? (‘.className’) gets all elements with class className, while \$\$(.className’)[0] and? (‘.className’)[1] gets the first and second elements, respectively.

Turn the browser into an editor

How many times have you wondered if you could edit some text in your browser? The answer is yes, you can turn your browser into a text editor. You can add and remove text anywhere in the DOM.

You no longer need to check the elements and edit the HTML. Instead, go to the developer console and type the following:

document.body.contentEditable=true 
Copy the code

This will make the content editable. Now, you can edit almost anything in the DOM.

Find events associated with elements in the DOM

Whenever you need to find event listeners for an element in the DOM during debugging, Google Console uses getEventListeners to make finding these events easier and more intuitive.

GetEventListeners ($(‘ selector ‘)) return an array of objects containing all the events bound to that element. You can expand objects to view events:

To find listeners for a particular event, do this:

GetEventListeners ($(' selector ')). EventName [0]. The listenerCopy the code

This displays the listeners associated with the particular event. Here eventName[0] is an array that lists all events for a particular event. Such as:

GetEventListeners ($(" firstName ")). Click [0]. The listenerCopy the code

The listener associated with the click event of the element with ID ‘firstName’ is displayed.

Monitor the event

If you want to monitor events that bind to specific elements in the DOM when they are executed, you can also do so from the console. You can use different commands to monitor some or all of these events:

If you want to monitor events that bind to specific elements in the DOM when they are executed, you can also do so from the console. You can use different commands to monitor some or all of these events:

  • MonitorEvents ($(‘ selector ‘)) monitors all events associated with the selector’s elements and then prints them to the console when they are triggered. For example, monitore($(#firstName)) prints all events for the element with ID firstName.

  • MonitorEvents ($(‘ selector ‘), ‘eventName’) prints the specific event bound to the element. You can pass the event name as an argument to the function. This will log only specific events bound to specific elements. For example, monitorEvents($(‘ #firstName ‘), ‘click’) prints all click events bound to an element with ID ‘firstName’.

  • Monitore ($(selector), [eventName1, eventName3′,.]) will record multiple events based on your own needs. Instead of passing a single event name as an argument, you pass an array of strings containing all events. For example, Monitore ($(#firstName), [click, focus]) records click events and focus events bound to the ID firstName element.

  • Unmonitorevent ($(selector)): This will stop monitoring and printing events in the console.

Check an element in the DOM

You can check an element directly from the console:

  • inspect((‘ # firstName))Will check the element with ID 'firstName',Spect ($(‘ a ‘)3)The fourth in the DOM will be checkedA ` elements.

  • $0, $1, $2, etc. will help you get the most recently checked elements. For example, $0 represents the last DOM element checked, and $1 is the next-to-last DOM element checked.

Retrieves the value of the last result

You can use the console as a calculator. When you do this, you may need to use the second to track one calculation. Here’s how to retrieve the results of previous calculations from memory:

The $_Copy the code

The process is as follows:

2+3+4
9 //- The Answer of the SUM is 9

$_
9 // Gives the last Result

$_ * $_
81  // As the last Result was 9

Math.sqrt($_)
9 // As the last Result was 81

$_
9 // As the Last Result is 9
Copy the code

Clear the console and memory

If you want to clear the console and its memory, type:

 clear()
Copy the code


The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, HERE I recommend a good BUG monitoring tool Fundebug.

Your likes are my motivation to keep sharing good things.

communication

Dry goods series of articles summarized as follows, feel good point Star, welcome to add groups to learn from each other.

Github.com/qq449245884…

I am Xiaozhi, the author of the public account “Big Move the world”, and a lover of front-end technology. I will often share what I have learned to see, in the way of progress, mutual encouragement!

Pay attention to the public number, background welfare, you can see the welfare, you know.