文章目录
- 6. 控制台打印(Console)
-
- 模拟Java日志打印格式
- 美化对象打印(表格形式打印输出)
- 日志等级输出(让其在控制台显示时有颜色提示)
- 代码运行时间统计打印输出
6. 控制台打印(Console)
官方文档: https://developer.mozilla.org/zh-CN/docs/Web/API/Console#用法
模拟Java日志打印格式
替换字符 | 作用 |
---|---|
%o | 对象(可看到内部结构) |
%s | 字符串 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
let people = {
name: "lrc",
year: 18
}
let article = {
id: "423432431sfsdf",
content: "测试控制台接口"
}
//不建议:这样打印不出对象内部结构
console.log("people:" + people + " article: " + article)
console.log("people:%s article: %s", people, article)
//建议 == 下面两种是一样的
console.log("people:", people, "article: ", article)
console.log("people:%o article:%o", people, article)
</script>
</html>
美化对象打印(表格形式打印输出)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
let people = {
name: "lrc",
year: 18
}
let article = {
id: "423432431sfsdf",
content: "测试控制台接口"
}
console.table(people)
console.table(article)
let arrays = [people,article]
console.table(arrays)
</script>
</html>
日志等级输出(让其在控制台显示时有颜色提示)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
console.error("错误日志哦!!!")
console.warn("警告日志哦!!!")
console.log("普通日志哦!!!")
</script>
</html>
代码运行时间统计打印输出
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
console.time("代码时间统计");
let people = {
name: "lrc",
year: 18
}
let article = {
id: "423432431sfsdf",
content: "测试控制台接口"
}
console.timeLog("代码时间统计");
//不建议:这样打印不出对象内部结构
console.log("people:" + people + " article: " + article)
console.log("people:%s article: %s", people, article)
//建议 == 下面两种是一样的
console.log("people:", people, "article: ", article)
console.log("people:%o article:%o", people, article)
console.timeLog("代码时间统计");
console.table(people)
console.table(article)
let arrays = [people,article]
console.table(arrays)
console.timeLog("代码时间统计");
console.error("错误日志哦!!!")
console.warn("警告日志哦!!!")
console.log("普通日志哦!!!")
console.timeEnd("代码时间统计");
</script>
</html>