✒️ 关于使用 JS 控制台 (console.log 和 console.table) 的一些🔥技巧
你们可能都看过“别用 console.log,用调试器!”这类帖子。当然,这话不无道理,但实际上,console.log 超级好用,而且是一种快速简便的调试方法。所以,让我们来学习一些 console 的实用、好用,甚至可能出乎意料的用例。
使用 console.log 在控制台上打印值非常清晰。例如,打印当前日期:
const now = new Date()
console.log(now)
如果使用多个不同的值执行此操作,很快就会变得混乱。为了保持整洁,我们还可以传递多个参数。这样就可以标记输出:
const now = new Date()
const tomorrow = new Date()
tomorrow.setDate(tomorrow.getDate() + 1)
console.log("now", now)
console.log("tomorrow", tomorrow)
当然,我们也可以只通过一次 console.log 调用来记录这两个值:
console.log(now, tomorrow)
或者,我们可以利用对象属性值的简写以及 console.log 处理对象的方式。这样,我们不再只是记录变量,而是记录一个动态创建的对象:
console.log({ now })
console.log({ tomorrow })
这会记录类似
{now: Sat Jan 11 2020 10:11:29 GMT+0100}
{tomorrow: Sun Jan 12 2020 10:11:29 GMT+0100}
太棒了!我们的变量就这样自动被标记了!
正如我们所谈论的记录对象 - 还有另一种使用来记录这些对象的好方法console.table
。
const luke = {
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male"
}
console.table(luke);
这将记录对象的整洁表格视图。
同样的方法也适用于数组和对象数组:
// let's have some objects (from the swapi.co)
const falcon = {
"name": "Millennium Falcon",
"model": "YT-1300 light freighter"
}
const starDestroyer = {
"name": "Star Destroyer",
"model": "Imperial I-class Star Destroyer"
}
const deathStar = {
"name": "Death Star",
"model": "DS-1 Orbital Battle Station"
}
// create an array of our objects
const starships = [falcon, starDestroyer, deathStar]
// and log them on the console in a neat table
console.table(starships)
输出将类似于以下内容:
想要提升 Web 开发能力?
🚀🚀🚀订阅我的每周✉️简报