The login
registered
Write an article
Home page
Download the APP

Console.log () also works like this

Can fly superman

Console.log () also works like this

If you were to rank the most commonly used programming statements by front-end developers, console.log() would be near the top of the list. But most people’s understanding of console.log() is that it simply prints text messages. But console.log() supports many more uses. Like this:




image.png

The implementation is simple:

console.log('%cHello world', 'font-size:100px; color:#f00; background:yellow; ');Copy the code

Console.log () can be used as a console. The console.log() argument can take one of four forms

  1. console.log(obj1 [, obj2, …, objN);
  2. console.log(msg [, subst1, …, substN);
  3. console.log(‘String: %s, Int: %d,Float: %f, Object: %o’, str, ints, floats, obj)
  4. console.log(The value of temp is: ${temp})

The arguments 1, 2, and 4 take the form of an object, a string, and a template string, which are easy to understand and won’t be discussed here. The third case allows string substitution.

Substitution string instructions
%o or %O Print JavaScript objects, which can be integers, strings, or JSON data.
%d or %i Print integers.
%s Print a string.
%f Prints floating point numbers.

Take this example

for (var i=0; i<5; i++) {
  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
}
Copy the code

The output




image.png

In addition, console.log() supports custom styles. Use this by prefacing the text to be customized with c%. Such as:

console.log('%cgreen text %cblue text %cred text ','color:green; ','color:blue','color:red; ')Copy the code

Output:




image.png

Note: When using replacement strings and custom styles, the first argument is the string template, and the following arguments replace the string template in order. If default, replacement strings and custom styles are not recognized. Take the following example:

console.log('%cgreen text %cblue text %cred text ','color:green; ','color:blue')Copy the code

Output:


image.png



%c
%c

In addition, console.info(),console.warn(), and console.error() all have similar uses for console.log().




image.png




image.png




image.png

While none of this is difficult, and how much practical value it has is debatable, there is something to be said for the pleasure of discovering, however small, some novel piece of knowledge you have never noticed before.

Reference link: developer.mozilla.org/zh-CN/docs/… Jingyan.baidu.com/article/911…