0%

javascript-console

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:
console-green-text
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:
alt text

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const obj = {
name: 'Philip',
gender: 'male',
address: {
company: {
name: 'google',
location: {
city: 'shanghai',
country: 'china',
},
},
},
};

console.log(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
2
3
4
5
{
name: 'Philip',
gender: 'male',
address: { company: { name: 'google', location: [Object] } }
}

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
2
3
4
5
6
7
8
9
10
{
name: 'Philip',
gender: 'male',
address: {
company: {
name: 'google',
location: { city: 'shanghai', country: 'china' }
}
}
}