每个人偶尔都会使用JavaScrip
t控制台进行日志记录或调试。但是控制台对象比得多console.log()
。
计算的属性名称
ES6计算的属性名称特别有用,因为它们可以通过在变量周围添加一对大括号来帮助您识别已记录的变量。
const x = 1, y = 2, z = 3;
console.log({x, y, z}); // {x: 1, y: 2, z: 3}
console.trace()
console.trace()
的工作原理与完全相同console.log()
,但它也输出整个堆栈跟踪,因此您确切地知道发生了什么。
const outer = () => {
const inner = () => console.trace('Hello');
inner();
};
outer();
/*
Hello
inner @ VM207:3
outer @ VM207:5
(anonymous) @ VM228:1
*/
console.group()
console.group()
允许您将日志分组为可折叠的结构,当您有多个日志时特别有用。
console.group('Outer'); // Create a group labelled 'Outer'
console.log('Hello'); // Log inside 'Outer'
console.groupCollapsed('Inner'); // Create a group labelled 'Inner', collapsed
console.log('Hellooooo'); // Log inside 'Inner'
console.groupEnd(); // End of current group, 'Inner'
console.groupEnd(); // End of current group, 'Outer'
console.log('Hi'); // Log outside of any groups
记录级别
有几个日志记录级别除了console.log()
,比如console.debug()
,console.info()
,console.warn()
和console.error()
。
console.debug('Debug message');
console.info('Useful information');
console.warn('This is a warning');
console.error('Something went wrong!');
console.assert()
console.assert()
提供了一种简便的方法,仅在断言失败时(即,当第一个参数为时false
)将某些内容记录为错误,否则将完全跳过该记录。
const value = 10;
console.assert(value === 10, 'Value is not 10!'); // Nothing is logged
console.assert(value === 20, 'Value is not 20!'); // Logs "Value is not 20!"
console.count()
您可以console.count()
用来计算一段代码执行了多少次。
Array.from({ length: 4 }).forEach(
() => console.count('items') // Call the counter labelled 'items'
);
/*
items: 1
items: 2
items: 3
items: 4
*/
console.countReset('items'); // Reset the counter labelled 'items'
console.time()
console.time()
提供了一种快速的方法来检查代码的性能,但由于其准确性较低,因此不应用于真正的基准测试。
console.time('slow comp'); // Start the 'slow comp' timer
console.timeLog('slow comp'); // Log the value of the 'slow comp' timer
console.timeEnd('slow comp'); // Stop and log the 'slow comp' timer
CSS
最后但并非最不重要的一点是,您可以在其中使用%c
字符串替换表达式console.log()
将CSS
应用于日志的各个部分。
console.log(
'CSS can make %cyour console logs%c %cawesome%c!', // String to format
// Each string is the CSS to apply for each consecutive %c
'color: #fff; background: #1e90ff; padding: 4px', // Apply styles
'', // Clear any styles
'color: #f00; font-weight: bold', // Apply styles
'' // Clear any styles
);
from: 30secondsofcode