美文网首页
充分利用console.log()

充分利用console.log()

作者: 涅槃快乐是金 | 来源:发表于2024-04-18 20:47 被阅读0次

    分享一些希望能改进你们日常使用的技巧!

    将变量包装在对象中

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


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

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

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


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

    对于对象使用 console.table()

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


    表格格式立即清楚地显示出我们在一个行中将 name拼写为names,以及在另一个行中忘记了一个id!

    对于函数和 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"
    );
    

    相关文章

      网友评论

          本文标题:充分利用console.log()

          本文链接:https://www.haomeiwen.com/subject/fojyxjtx.html