您好,欢迎访问一九零五行业门户网

利用Js的console对象,在控制台打印调式信息测试Js的实现

一次偶然的机会,打开百度的时候按下了f12,然后就见控制台里面输出了百度的招聘广告,感觉挺帅气的,再然后就有了这篇博文。
既然可以这样在控制台输出信息,那以后再调试js的时候不就可以省去很多麻烦了嘛!避免不误人子弟,特意使用for(var i in console)查看了下各种浏览器控制台对console的支持,
结果如下:
ie 11 控制台
log , info , warn , error , debug , assert , time , timeend , group , groupcollapsed , groupend , trace , clear , dir , dirxml , count , countreset , cd , select , profile , profileend
firebug 控制台
log , debug , info , warn , exception , assert , dir , dirxml , trace , group , groupcollapsed , groupend , profile , profileend , count , clear , time , timeend , timestamp , table , error
chrome 控制台
memory , _commandlineapi , debug , error , info , log , warn , dir , dirxml , table , trace , assert , count , marktimeline , profile , profileend , time , timeend , timestamp , timeline , timelineend , group , groupcollapsed , groupend , clear
可以看出,以上我测试的浏览器对 log , info , warn , error , debug 五个基本方法都是支持的,注意,我使用的是 ie 11,其他版本我没测试,而 firefox 本身也是不带控制台的,需要加载firebug 插件并且启动它,才能console,否则就是js报错了。为了使用起来更方便,可以自己封装一下,判断一下浏览器对 console 的支持,不支持就只能使用原始的 alert 或者其他方法了。
简单用法:
console.log(日志信息);
console.info(一般信息);
console.debug(调试信息);
console.warn(警告提示);
console.error(错误提示);
格式化输出:
console.log(%d年%d月%d日, 2014, 5, 20);//日期格式输出
console.log('%c有颜色的输出信息', 'color:white; background-color:#0055cc');//格式输出
输出变量:
var who= 'you';
console.log('输出变量 we support  ', you);//读取变量
输出数组:
var arr = [1, 2, 3, 4, 5];
console.log('数组:', arr);//输出数组
其它类似信息

推荐信息