JavaScript console 四个实用功能
相信每个 JavaScript 开发者 都使用过 console.log("msg")。
除此之外,你还使用过哪些?
1. log() | info() | debug() | warn() | error
上面展示的五个方法,都是打印信息,你可以传一个或者多个参数。
console.log("log");
console.info("info");
console.debug("debug");
console.warn("warn");
console.error("error");
通过比对效果,可以将log() | info() | debug()归类,这也难怪使用info()和debug()这两个方法的频率少。
console.log() 加入样式之后,在控制台上展示的内容比较有意思。通常会在各大平台系统上加入招聘广告之类的内容。比如百度的网页。
其实就是使用 %c 符号命令,应用 CSS 样式。如下:
console.log("%c 红色的文本, 14号粗字体", "color: red; font-size: 14px; font-weight: bolder;")
感兴趣的读者可以到百度控制台上比对一下效果。嗯,这些控制台招聘信息,看起来有些酷,你还可以实现更酷的,比如下面这个:
Function.prototype.makeMulti = function () {
let l = new String(this)
l = l.substring(l.indexOf("/*") + 3, l.lastIndexOf("*/"))
return l
}
let string = function () {
/*
_ __ __ __ _____ ______
| | / / \ \ / / / ___| |___ /
| | __ / / \ \/ / | | / /
| | / | / / } { | | _ / /
| |/ |/ / / /\ \ | |_| | / /__
|___/|___/ /_/ \_\ \_____/ /_____|
*/
}
if (window.console) {
console.log(string.makeMulti());
console.log("欢迎来到%c无效工作%c演示区", "color:red;font-weight:bold;", "");
}
可是使用 console.log() 在生产环境上,说好听点,是产品打磨,但是 鸡肋。
扯远了~ 回归正题
2. table()
console.table() 用来展示数组或对象的数据。
let arr = [{
firstName: 'John',
lastName: 'Doe',
age: 2
},
{
firstName: 'William',
lastName: 'Shakespeare',
age: 3
}];
console.table(arr);
当然,你还可以指定展示哪些列,比如只是展示上面 的 firstName 和 lastName 数据。
let arr = [{
firstName: 'John',
lastName: 'Doe',
age: 2
},
{
firstName: 'William',
lastName: 'Shakespeare',
age: 3
}];
console.table(arr, ['firstName', 'lastName']);
当然,当数组或者对象进行嵌套的时候,展示的效果就不理想了,比如:
let obj = {
name: "jimmy",
children: {
name: "neo"
}
};
console.table(obj);
在视觉呈现上,一层数据,console.table() 比 console.log() 要佳。
3. group() 和 groupEnd()
使用分组功能,对你的数据更加有层级掌控。刚才的 table() 处理多层级功能的时候处理能力很差。那么多层级的数据可以考虑以下面的方式呈现。
console.group();
console.log("层级1");
console.group();
console.log("层级1-1");
console.log("层级1-2");
console.groupEnd();
console.log("层级2");
console.group();
console.log("层级2-1");
console.groupEnd();
console.groupEnd();
这有点像 HTML 中的 ol有序 或 ul无序列表。
嗯...在权限管理或者查看多层数据格式的时候,这个打日志的方式还是比较友好地进行数据比对的。
至于其他的场景应用,还是 console.log() 好用。
4. time() 和 timeEnd()
检查你代码运行的性能。
console.time('Time')
let count = 0;
for(let i = 0; i < 100; i++) {
count += i;
}
console.log("total: ", count);
console.timeEnd('Time');
如果你做的业务跟图表相关的内容,比如金融基金,也许这个功能对你很有帮助。
评论已关闭