调试JAVASCRIPT,不再用ALERT了(一)

chrome浏览器控制台可以直接看到输出信息,不需要安装什么插件!

JavaScript这东西实在是强大,可惜就是没有个强大的ide来支持

写JavaScript最郁闷的莫过于调试了,太麻烦了

以前就是不断的alert,然后就不断的按确定

或者来个比较进阶版的

document.title = "this is my debug info";

 

再来个高级的,直接抛异常,不过貌似在IE7抛异常,只显示了发现异常,却没有显示异常信息。

在FF下用Firebug就可以显示

if(typeof(e) == "undefined")
    
throw("e is undefined");

或者直接抛出个Error

var err = new Error();
err.name 
= "first error";
err.message 
= "first error message";
throw(err);

好,我们对Error适当的修饰一下

复制代码
function error(type, message){
    
var err = new Error();
    err.name 
= type + "Error";
    err.message 
= message;
    
throw(err);
}

if(typeof(e) == "undefined") {
    error(
'a var',"e is undefined");
}
复制代码

Firebug提供了console对象,可以向控制台输出控制信息,这种方式本人觉得更加优越

 

console.warn("显示警告,显示警告图标");
console.error(
"显示恐怖的错误图标");
console.log(
"这个不错参数可以使Object,[Object,Object]");

 

什么?没有装Firebug,倒~~

Firebug的Console API

 

每个用Firefox加载的页面,Firebug都添加了一个全局变量console,通过这个变量的若干方法,你可以通过脚本向控制台输出各种调试信息。

console.log(object[, object, ...])

往控制台写一条信息,可以有多个参数,甚至可以像printf那样格式化出去,例如

console.log("The %s jumped over %d tall buildings", animal, count);

或者这样:

console.log("The", animal, "jumped over", count, "tall buildings");
console.log("I am %s and I have:", myName, thing1, thing2, thing3);
下面是格式化参数表:

String Substitution Patterns
%s String
%d, %i Integer (numeric formatting is not yet supported)
%f Floating point number (numeric formatting is not yet supported)
%o Object hyperlink

console.debug(object[, object, ...])

向控制台输出一条信息,同时包含了跳往调用行的链接

console.info(object[, object, ...])

向控制台输出一条信息,前面显示“信息”图标,同样包含了跳往调用行的链接

console.warn(object[, object, ...])

向控制台输出一条信息,前面显示“警告”图标,同样包含了跳往调用行的链接

console.error(object[, object, ...])

向控制台输出一条信息,前面显示“错误”图标,同样包含了跳往调用行的链接

console.assert(expression[, object, ...])

校验是否符合表达式,如果不符合,将向控制台输出错误信息,并且抛出异常

console.dir(object)

输出对象的所有属性,可以在DOM标签中看到详细信息

console.dirxml(node)

输出HTML或XML元素的XML代码树,可以再HTML中查看详细的情况

console.trace()

Prints an interactive stack trace of JavaScript execution at the point where it is called.

The stack trace details the functions on the stack, as well as the values that were passed as arguments to each function. You can click each function to take you to its source in the Script tab, and click each argument value to inspect it in the DOM or HTML tabs.

console.group(object[, object, ...])

分组输出,和console.groupEnd()配合使用,知道下一个console.groupEnd()出现,就闭合分组

console.groupEnd()

和console.group()配合使用

console.time(name)

创建一个定时器,知道调用console.time(name),才停止该定时器计时

console.timeEnd(name)

和console.time(name)配合使用

console.profile([title])

Turns on the JavaScript profiler. The optional argument title would contain the text to be printed in the header of the profile report

console.profileEnd()

Turns off the JavaScript profiler and prints its report

console.count([title])

 计数器,每执行一次,该title的值就累加1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章