JavaScript Console
console
对象是JavaScript的一个全局对象,它提供了控制台的操作方法和属性。控制台是浏览器提供的一个调试工具,它可以用来输出信息、查看变量的值、查看调用栈等。
colored log
In JavaScript, you can output colored logs to the console using the %c directive in console.log(). Here’s an example:
1 | console.log("%cThis is a green text", "color:green; font-size: 18px"); |
output:
In this example, %c is used as a placeholder for the styles that are specified in the second argument. The text “This is a green text” will be displayed in green color in the console.
You can also specify multiple styles:
1 | console.log("%cThis is a blue text on yellow background", "color:blue; background-color:yellow"); |
output:
In this example, the text will be blue and the background color will be yellow.
console.dir()
To print a deeply nested object in a more readable way, you can use console.dir().
1 | const obj = { |
output: Notice that the location object is printed as [Object] which is unreadable(unreadable in Node.js, it’s OK to run in Browser console).
1 | { |
Usually, we resolve this by using JSON.stringify() to convert the object to a string.
1 | console.log(JSON.stringify(obj)); |
but this method has a limitation: it only works for objects that are serializable to JSON. If the object contains circular references, it will throw an error.
1 | console.dir(obj); |
output:
1 | { |