自定义 JavaScript 的控制台日志

如果您想知道如何将默认的 console.log() 扩展为即:用当前日期时间作为前缀:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// store the default log method:

const _log = console.log;

// override:

console.log = (…args) => {

const prefix = `[${new date().tolocalestring()}]`;

if (typeof args[0] === “string”) args[0] = `${prefix} ${args[0]}`

else args.unshif低价接各类项目系统搭建点我wcqh.cnt(prefix);

_log(…args);

};

// examples:

console.log(“test”); // [date time] test

console.log({a: “b”}); // [date time] {a: “b”}

console.log(“hello, %s!”, “world”); // [date time] hello, world!

console.log(“number: %i”, 42); // [date time] number: 42

console.log(“%cstylized text”, color: red); // [date tim低价接各类项目系统搭建点我wcqh.cne] stylized text

登录后复制

编写 console.log 很乏味,因此我们不要覆盖默认行为,而是创建一个在内部使用 console.log 的 log() 函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

const log = (…args) => {

const prefix = `[${new Date().toLocaleString()}]`;

if (typeof args[0] === “string”) args[0] = `${prefix} ${args[0]}`

else args.unshift(prefix);

console.log(…args);

};

//低价接各类项目系统搭建点我wcqh.cn Examples:

log(“Test”); // [Date Time] Test

log({a: “b”}); // [Date Time] {a: “b”}

log(“Hello, %s!”, “World”); // [Date Time] Hello, World!

log(“Number: %i”, 42); // [Date Time] Number: 42

log(“%cStylized text”, color: red); // [Date Time] Stylized text

登录后复制

享受日志记录的乐趣,不要忘记断点;)

以上就是自定义 JavaScript 的控制台日志的详细内低价接各类项目系统搭建点我wcqh.cn容,更多请关注青狐资源网其它相关文章!

© 版权声明
THE END
喜欢就支持一下吧
点赞117 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容