现在,假设您正在编写一些JS代码,但它无法正常工作。你做的第一件事是什么?你是Console.log 它!因此,我将告诉您 Console.log 的一些替代方案。
通过使用 javascript 对象的破坏能力,您可以这样做:
const { log } = console;log("hi");log("testing");
你可以将log函数更改为您想要的任何其他名称,如下所示:
const { log: myLog } = console;myLog("hi");myLog("testing");
曾经想对您的日志进行分组吗?这个方法很适合你!
console.group("groupName");console.log("hi");console.log("testing");console.groupEnd();console.group("groupName2");console.log("hi");console.log("testing");console.groupEnd();
不错吧?
用于打印数组。
const arr = [1, 2, 3, 4, 5];console.table(arr);
此方法用于测量时间。例如,检查完成 x 任务花了多少秒?
console.time("test");setTimeout(() => { console.timeEnd("test");}, 1000);
这将为我们提供以下结果:
test: 1.000s
此方法用于检查条件是否为真。如果不是,它将引发错误。
console.assert(/** Condition **/, /** Error message **/);console.assert(1 === 1, "1 is equal to 1"); // No errorconsole.assert(0 === [], "0 is equal to []"); // Error in the console
计算某件事发生的次数。
console.count("counter 1");for (let i = 0; i < 10; i++) { i % 2 == 0 ? console.count("counter 1") : console.count("counter 2");}
这给了我们以下结果:
此方法跟踪它被调用的位置。我有一个这样的 HTML 文件:
Document
现在你可以看到在哪里 console.trace 被调用了。
您可能没有听说过该debugger关键字。它是一个用于停止代码执行的关键字。
const buggyCode = () => { debugger; console.log("hi");};// ...buggyCode();console.log("World");
这会暂停代码的执行,您可以看到如下内容:
它会告诉您调试器的调用位置。
感谢你阅读本教程。希望您已经学到了一些新东西并准备好开始使用它。
留言与评论(共有 0 条评论) “” |