---
title: "【转】Js也有console对象，在控制台打印调试再好不过 "
author: "rmzdb"
date: "2014-11-04T18:17:47Z"
tags: []
slug: "js-console"
draft: false
lastmod: "2014-11-04T18:17:47Z"
id: 2152362
url: "https://rmzdb.iteye.com/blog/2152362"
---

今天在看jq的代码时看到这样一个代码

console.warn( "nothing selected, can't validate, returning nothing" );

单独运行，居然在控制台打印出了nothing selected, can't validate, returning nothing，

豁然开朗，既然可以这样在控制台打印出消息，那以后就省得麻烦去用什么alert或是按F10去逐行调试了，肯定可以节省不少时间。

特意使用for(var i in console)查看了下各种浏览器控制台对console的支持，如下

IE控制台  
**log info warn error** assert dir clear profile profileEnd

Firebug控制台  
**log info warn error** debug exception assert dir dirxml trace group groupEnd groupCollapsed time timeEnd profile profileEnd count clear table notifyFirebug firebug

Chrom控制台  
profiles memory debug **error info log warn** dir dirxml trace assert count markTimeline profile profileEnd time timeEnd group groupCollapsed groupEnd

Opera控制台

time timeEnd trace profile profileEnd debug **log info warn error** assert dir dirxml group groupCollapsed groupEnd count table

可以看出，四种浏览器对**log、info、warn、error**四个基本方法都是支持的，除了IE，其他三种还支持个debug，所以使用debug要注意，当然咯，平时打印调试什么的，用log就行。还有个问题，IE6/7没有开发人员工具，也就没有控制台，而FF本身也是不带控制台的，需要加载Firebug插件并且启动它，才能console，否则就是js报错了。

所以为了使用起来无这种后顾之忧，还是建议自己封装一个打印类，如logger，在其中检测当然环境对console的支持，然后调用console的打印方法，不支持就用alert或其他方法咯，并且可以设置一个开关，标识是否需要打印以及打印级别，类似log4j，哈哈，这样使用起来就方便了。马上来写，写好了再分享下。