console.log、调试辅助函数、调试小技巧javascript
⚠️⚠️⚠️ 请注意本文不是讲 console 各类方法,请不要点出去。java
原本想取名为 console
黑魔法,顺手讲一点 console
的其余方法。但是查阅资料的时候发现好多文章都已经写得很是好了,这部分相关的内容你们能够到掘金
查看 👉 传送门。git
今天来说点不同的,其实有了那么多 console
方法开发中最常常用到的仍是 console.log
,那你知道怎么让 console.log
来帮你摸 🐟 减小 Debug 工做量嘛?github
ps: 固然天下除虫,惟断点调试不破。chrome
在开发时最常常碰到的场景之一就是函数嵌套了:bash
star(
pushmetop(
github('ok!')
)
)
复制代码
好家伙这嵌套够深,若是前方产品八米加急找到你说请求 star 函数出错了,一脸视死如归的同窗打开对应代码开始调试:微信
const a = github('ok!');
console.log(a);
const b = pushmetop(a);
console.log(b);
const c = star(b);
console.log(c);
复制代码
好家伙满满当当的魔术变量和 console.log
,这显然会减小大量摸🐟时间,机智的咱们为什么不对 console.log
进行升级:iphone
const superme = (x) => (console.log(x), x)
复制代码
小技巧:利用逗号表达式来写写出优雅的代码,例如
x => (x=x+1, x)
。函数
这下再除虫简直不要太舒服,简直指哪打哪
:测试
star(pushmetop(
// 想除哪就除拿
superme(github('ok!'))
))
复制代码
除了 iphone 有 plus 咱们的 debug
怎么可能没有呢?
const supermePlus = (x, fn = (y) => y) => fn(x)
复制代码
有了 supermePlus 咱们能够在调试的时候方便的插入调试代码:
star(
// 想怎么加就怎么加
supermePlus(pushmetop(github('ok!')), (x) => {
// 测试 x 是否是数字
console.log(typeof x === 'number' && x === x);
return x;
})
);
复制代码
也能够方便的替换值:
star(
supermePlus(pushmetop(github('ok!')), (x) => 'good!')
);
复制代码
在新版的 chrome 已经能够直接输出函数内容了。
在调试时打印函数时,每每会输出一段字符串:
const user = {
greet: function () {
console.log('hello world')
}
}
// 输出: [Function: greet]
console.log(user.greet)
复制代码
可是在须要参看函数详情时能够利用拼接字符串来实现:
const user = {
greet: function () {
console.log('hello world')
}
}
console.log(user.greet + '')
复制代码
function () {
console.log('hello world')
}
复制代码
提供一个简单的函数定义,方便你们测试本文章中的代码
const github = x => x;
const pushmetop = x => x + '!';
const star = x => x + '?';
复制代码
在困惑的城市里总少不了并肩同行的
伙伴
让咱们一块儿成长。
点赞
。小星星
。m353839115
。本文原稿来自 PushMeTop