还在用alert简单粗暴的调试js,试试Chrome的console工具吧。
打开Chrome按下F12,进入Console选项卡,进入console模式。
1.使用断言调试工具console.assert()
如:
var num = 100; console.assert(num == 100);
断言失败会报错。
2.调试过多的信息,需要清除屏幕,使用console.clear()
3.console.count()记录函数调用次数,对于调试递归函数很有用。如:
var func = function (n) { console.count("func call"); if (n == 0) {return 1;} return n * arguments.callee(n - 1);} func(10);
可以显示函数调用的次数,如下:
func call: 1 VM558:2 func call: 2 VM558:2 func call: 3 VM558:2 func call: 4 VM558:2 func call: 5 VM558:2 func call: 6 VM558:2 func call: 7 VM558:2 func call: 8 VM558:2 func call: 9 VM558:2 func call: 10 VM558:2 func call: 11 VM558:2 3628800
4.找到对象的属性,类似Python的dir(model)可以使用console.dir(object),
如:
console.dir(func);
5.console.dirxml()简单解析xml
如note.xml文件在浏览器打开以后:
<!-- Edited by XMLSpy --> <note> <to id="tove">Tove <h1>gcc</h1> </to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
使用console.dirxml()解析如下:
var x = document.querySelector('#tove'); console.dirxml(x);
6. console.error()记录错误,如:
var funone = function() {if (arguments.length != 2) {console.error("error is %s", "arguments");}} funone(1); funone(1, 1, 2);
可以提示自定义错误
7. console.group() 为日志组记录一个title,使用console.gourpEnd();结束
console.group("This is title");console.error("error is %s", "arguments");console.gourpEnd();
8. console.log() 的格式化操作,可以为log增加样式表,需要在string前加%c, 如:
console.log("%cThis is %s speaking: %s", "color:green;background:black;", "Crusher", "Hello Chrome");
9. 测试js代码段运行时间,time()和timeEnd()中参数需要一样,如:
console.time('ok'); var s = 1; for (var i = 0; i < 100000; i++) {s += i;} console.timeEnd('ok');
ok: 19024.000ms
10. console.warn() 用于得到警告信息。和console.log() 类似
11. 开始debugger session,在任意代码段中加入debugger; 可以在执行到相关代码附近时跳转到debugger;附近。
12. console.trace() 显示调用栈过程,类似Linux的strace,如:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <body> <script> function added(a, b) { return a + b; } function world() { console.trace(); var resworld = added(1 , 2); return resworld; } function hello() { var s = 1; console.trace(); var res = world(); return s + res; } console.trace(); hello(); </script> </body> </html>
这些调试方法可以很好的帮大家调试js,不过要记得最后都删除掉就好了。
更多方法见官方说明:https://developers.google.com/chrome-developer-tools/docs/console-api#consoletimelabel