[JS] 前端充分使用console.log()有效输出(2024-6-1)

将变量包装在对象中

不要使用 console.log(url, url2, baz),而是使用 console.log({ url, url2, baz })。

如果你比较这两者,你会发现这有多么有用:拥有 url 和 url2 键可以避免这两个 URL 之间的混淆。

在日志前加上唯一字符串前缀

在应用程序的多个地方记录日志时,想出一个唯一的前缀并在所有日志中使用它是很有用的。这样可以更容易地在控制台中搜索和过滤日志。


搜索 debug-issue:准确定位日志查询信息,如果有其他无关的日志在其中,这将节省你很多时间。

对于对象使用 console.table()

当打印多个结构相似的对象时,console.table()是 console.log()的一个更强大的可视化替代方案。

表格格式立即清楚地显示出我们在一个行中将 name。

对于函数和 DOM 元素使用 console.dir()

console.dir()在帮助你调查复杂的原型时非常有用,因为它们的 toString() 输出并不能揭示所有信息。

让我们看看输出:

你可以看到 console.log 提供了函数的字符串化版本,而console.dir 则提供了许多其他属性。真正酷的是,如果你点击[[FunctionLocation]]链接,它会显示该函数的源代码:


同样,你会看到 DOM 元素的输出在console.dir中更加详细,因为你可以看到 DOM 元素的每一个属性:

为你的 console.logs 添加样式

你可以为你的 console.log 语句添加样式。

console.log(
  // What comes after %c is what the styles will apply to
  "This is %cMy stylish message",
  // you can add multiple properties:
  "color: yellow; font-style: italic; background-color: blue;padding: 2px"
);

// You could also style different parts of the console with multipule %c's:
console.log(
  "Multiple styles: %cred %corange",
  // style for first %c
  "color: red",
  // style for second %c
  "color: orange",
  // for every %c you can add more styles with ","

  "Additional unformatted message"
);

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值