今天主要讲的时console.log()
简单介绍一下console.log()
方法
主要用于在控制台输出信息,该方法对于开发过程进行测试很有帮助。
1.你是否知道可以在console.log 中传递参数?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
console.log('Let us %s a string', 'print ');
// Let us print a string
console.log('The number %d is not the same as %i', 10,11);
// The number 10 is not the same as 11
console.log('Even a float like %f will work', 10.233);
// Even a float like 10.233 will work
console.log('There is a good link: %o', 'http://www.baidu.com');
// There is a good link:"http://www.baidu.com'"
</script>
</body>
</html>
console.log 中的参数类型
字符串:使用%s 整数:使用%d或%i 浮动:使用%f 对象超链接:使用%o
这些类型绰绰有余,可以派上用场!
要使用参数,我们可以将它们放在控制台日志中,如下所示:
console.log('This %s will return the number %d', 'string', 10);
// This string will return the number 10
如您所见,我们可以一次给它多个参数。这些按输入的顺序读取。
所以在上面的例子中,它将是先执行%s
然后 %d
。
反过来执行试试,发现%s和10可以对上,只是,string转%d不太行
2.最后补充一下其他的Console API
console.info()
// 输出提示信息
console.error()
// 输出错误信息
console.warn()
// 输出警示信息
console.debug()
// 输出调试信息
console.dir()
// 将DOM节点以DOM树的结构进行输出,可以查看对象的方法。
console.debug(object[, object, ...])
// 向控制台输出一条信息,它包括一个指向该行代码位置的超链接。
console.info(object[, object, ...])
// 向控制台输出一条信息,该信息包含一个表示“信息”的图标,和指向该行代码位置的超链接。
console.assert(expression[, object, ...])
// 断言,测试一条表达式是否为真,不为真时将抛出异常(断言失败)。
console.dirxml(node)
// 输出一个 HTML 或者 XML 元素的结构树,点击结构树上面的节点进入到 HTML 面板。
console.trace()
// 输出 Javascript 执行时的堆栈追踪。
console.group(object[, object, ...])
// 输出消息的同时打开一个嵌套块,用以缩进输出的内容。调用 console.groupEnd() 用以结束这个块的输出。
console.groupCollapsed()
// 同 console.group(); 区别在于嵌套块默认是收起的。
console.time(name)
// 计时器,当调用 console.timeEnd(name);并传递相同的 name 为参数时,计时停止,并输出执行两条语句之间代码所消耗的时间(毫秒)。
console.profile([title])
// 与 profileEnd() 结合使用,用来做性能测试,与 console 面板上 profile 按钮的功能完全相同。
console.count([title])
// 输出该行代码被执行的次数,参数 title 将在输出时作为输出结果的前缀使用。
console.clear()
// 清空控制台