千家信息网

怎么使用JS console.log函数

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,这篇文章主要讲解了"怎么使用JS console.log函数",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么使用JS console.log函数"吧
千家信息网最后更新 2025年02月01日怎么使用JS console.log函数

这篇文章主要讲解了"怎么使用JS console.log函数",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么使用JS console.log函数"吧!

1. console.assert()

只想输出选定日志时这一指令非常实用,它将只输出错误参数,如果第一个参数正确,它就不起作用。

断言(assertion)

2. console.group() & console.groupEnd( )

可以使用控制台将消息分组。

将消息分组

3. console.trace()

该方法会追踪并显示代码在何时终止运行。

追踪

4. console.count()

该函数记录count()函数的调用次数,有一个可选的参数label。

如果调用时提供了label,该函数将记录使用该特定label调用count()的次数。

如果调用时省略label,函数将记录在这一行调用count()的次数。

计数

5. console.table ()

希望看到合适易读的JSON文本吗?

对数组进行更好的可视化处理!

6. 在控制台消息中添加样式

所有控制台消息看起来都一样吗?现在就不一样了,让调试日志中重要的部分看起来更加醒目。

带颜色的消息

可以通过以下方式改变日志中特定单词的颜色:

高亮显示特定单词

7. console.time()

console.time()用于跟踪操作耗时,它是跟踪JavaScript执行所耗费的短暂时间的好方法。

8. 控制台中的HTML

从控制台中获取HTML元素,跟检查元素的方式相同。

HTNL元素展示

9. console.dir()

输出指定对象的JSON形式。

10. console.memory( )

想知道Javascript应用占用了多少浏览器内存?

内存

11. 使用占位符

各种不同的占位符如下所示:

  • %o :接受一个对象,

  • %s :接受一个字符串

  • %d :接受一个小数或整数

占位符介绍

12. console.log() | info( ) | debug( ) | warn( ) | error( )

这些语句将根据事件的类型用不同颜色标识原始字符串。

13. console.clear( )

最后但也很重要的一点是,使用clear()命令清除所有控制台消息。

以下是要点补充。

// time and time end console.time("This"); let total =0; for (let j =0; j <10000; j++) { total += j } console.log("Result", total); console.timeEnd("This"); // Memory console.memory() // Assertion consterrorMsg='Hey! The number is not even'; for (let number =2; number <=5; number +=1) { console.assert(number %2===0, {number: number, errorMsg: errorMsg}); } // Count for (let i =0; i <11; i++) { console.count(); } // group & groupEnd console.group(); console.log('Test message'); console.group(); console.log('Another message'); console.log('Something else'); console.groupEnd(); console.groupEnd(); // Table constitems= [ { name:"chair", inventory:5, unitPrice:45.99 }, { name:"table", inventory:10, unitPrice:123.75 }, { name:"sofa", inventory:2, unitPrice:399.50 } ]; console.table(items) // Clear console.clear() // HTML Element let element =document.getElementsByTagName("BODY")[0]; console.log(element) // Dir constuserInfo= {"name":"John Miller", "id":2522, "theme":"dark"} console.dir(userInfo); // Color console.log('%cColor of the text is green plus small font size', 'color: green; font-size: x-small'); // pass object, variable constuserDetails= {"name":"John Miller", "id":2522, "theme":"dark"} console.log("Hey %s, here is your details %o in form of object", "John", userDetails); // Default console.log('console.log'); console.info('console.info'); console.debug('console.debug'); console.warn('console.warn'); console.error('console.error');

感谢各位的阅读,以上就是"怎么使用JS console.log函数"的内容了,经过本文的学习后,相信大家对怎么使用JS console.log函数这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

0