console对象是JavaScript的原生对象,它有点像Unix系统的标准输出stdout和标准错误stderr,可以输出各种信息到控制台,并且还提供了很多额外的有用方法
它的常见用途有两个:
1.调试程序,显示网页代码运行时的错误信息。
2.提供了一个命令行接口,用来与网页代码互动。
console对象提供的各种方法,用来与控制台窗口互动。
log(),info(),debug()
console.log方法用于在console窗口输出信息。它可以接受多个参数,将它们的结果连接起来输出。
console.log('Hello World')
// Hello World
console.log('a', 'b', 'c')
// a b c
console.log方法会自动在每次输出的结尾,添加换行符。
console.log(1);
console.log(2);
console.log(3);
// 1
// 2
// 3
如果第一个参数是格式字符串(使用了格式占位符),console.log方法将依次用后面的参数替换占位符,然后再进行输出。
console.log(' %s + %s = %s', 4, 1, 5)
// 4 + 1 = 5
上面代码中,console.log方法的第一个参数有三个占位符(%s),第二、三、四个参数会在显示时,依次替换掉这个三个占位符。
console.log方法支持以下占位符,不同格式的数据必须使用对应格式的占位符。
**%s 字符串
%d 整数
%i 整数
%f 浮点数
%o 对象的链接
%c CSS格式字符串**
var number = 11 * 9;
var color = 'red';
console.log('%d %s balloons', number, color);
// 99 red balloons
上面代码中,第二个参数是数值,对应的占位符是%d,第三个参数是字符串,对应的占位符是%s。
使用%c占位符时,对应的参数必须是CSS语句,用来对输出内容进行CSS渲染。
console.log('%cThis text is styled!',
'color: red; background: yellow; font-size: 24px;'
)
上面代码运行后,输出的内容将显示为黄底绿字。
如果参数是一个对象,console.log会显示该对象的值。
console.log({foo: 'bar'})
// Object {foo: "bar"}
console.log(Date)
// function Date() { [native code] }
console.info()和console.debug()都是console.log方法的别名,用法完全一样。只不过console.info方法会在输出信息的前面,加上一个蓝色图标。
warn(),error()
warn方法和error方法也是在控制台输出信息,它们与log方法的不同之处在于,warn方法输出信息时,在最前面加一个黄色三角,表示警告;error方法输出信息时,在最前面加一个红色的叉,表示出错,同时会显示错误发生的堆栈。其他方面都一样。
console.error('Error: %s (%i)', 'Server is not responding', 500)
// Error: Server is not responding (500)
console.warn('Warning! Too few nodes (%d)', document.childNodes.length)
// Warning! Too few nodes (1)
可以这样理解,log方法是写入标准输出(stdout),warn方法和error方法是写入标准错误(stderr)。
table()
对于某些复合类型的数据,console.table方法可以将其转为表格显示。
var languages = [
{ name: "JavaScript", fileExtension: ".js" },
{ name: "TypeScript", fileExtension: ".ts" },
{ name: "CoffeeScript", fileExtension: ".coffee" }
];
console.table(languages);
上面代码的language变量,转为表格显示如下。
复合型数据转为表格显示的条件是,必须拥有主键。对于数组来说,主键就是数字键。对于对象来说,主键就是它的最外层键。
var languages = {
csharp: { name: "C#", paradigm: "object-oriented" },
fsharp: { name: "F#", paradigm: "functional" }
};
console.table(languages);
上面代码的language,转为表格显示如下。
count()
count方法用于计数,输出它被调用了多少次。
function greet(user) {
console.count();
return 'hi ' + user;
}
greet('bob')
// : 1
// "hi bob"
greet('alice')
// : 2
// "hi alice"
greet('bob')
// : 3
// "hi bob"
上面代码每次调用greet函数,内部的console.count方法就输出执行次数。
该方法可以接受一个字符串作为参数,作为标签,对执行次数进行分类。
function greet(user) {
console.count(user);
return "hi " + user;
}
greet('bob')
// bob: 1
// "hi bob"
greet('alice')
// alice: 1
// "hi alice"
greet('bob')
// bob: 2
// "hi bob"
上面代码根据参数的不同,显示bob执行了两次,alice执行了一次。
dir(),dirxml()
dir方法用来对一个对象进行检查(inspect),并以易于阅读和打印的格式显示。
console.log({f1: 'foo', f2: 'bar'})
// Object {f1: "foo", f2: "bar"}
console.dir({f1: 'foo', f2: 'bar'})
// Object
// f1: "foo"
// f2: "bar"
// __proto__: Object
上面代码显示dir方法的输出结果,比log方法更易读,信息也更丰富。
该方法对于输出DOM对象非常有用,因为会显示DOM对象的所有属性。
console.dir(document.body)
dirxml方法主要用于以目录树的形式,显示DOM节点
console.dirxml(document.body)
如果参数不是DOM节点,而是普通的JavaScript对象,console.dirxml等同于console.dir
console.dirxml([1, 2, 3])
// 等同于
console.dir([1, 2, 3])
assert()
assert方法接受两个参数,第一个参数是表达式,第二个参数是字符串。只有当第一个参数为false,才会输出第二个参数,否则不会有任何结果。
console.assert(true === false, '判断条件不成立')
// Assertion failed: 判断条件不成立
time(),timeEnd()
这两个方法用于计时,可以算出一个操作所花费的准确时间。
console.time('Array initialize');
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
array[i] = new Object();
};
console.timeEnd('Array initialize');
// Array initialize: 1914.481ms
time方法表示计时开始,timeEnd方法表示计时结束。它们的参数是计时器的名称。调用timeEnd方法之后,console窗口会显示“计时器名称: 所耗费的时间”。
profile(),profileEnd()
console.profile方法用来新建一个性能测试器(profile),它的参数是性能测试器的名字。
console.profile('p')
// Profile 'p' started.
console.profileEnd方法用来结束正在运行的性能测试器。
console.profileEnd()
// Profile 'p' finished.
打开浏览器的开发者工具,在profile面板中,可以看到这个性能调试器的运行结果。
group(),groupend(),groupCollapsed()
console.group和console.groupend这两个方法用于将显示的信息分组。它只在输出大量信息时有用,分在一组的信息,可以用鼠标折叠/展开。
console.group('Group One');
console.group('Group Two');
// some code
console.groupEnd(); // Group Two 结束
console.groupEnd(); // Group One 结束
console.groupCollapsed方法与console.group方法很类似,唯一的区别是该组的内容,在第一次显示时是收起的(collapsed),而不是展开的。
console.groupCollapsed('Fetching Data');
console.log('Request Sent');
console.error('Error: Server not responding (500)');
console.groupEnd();
上面代码只显示一行”Fetching Data“,点击后才会展开,显示其中包含的两行。
trace(),clear()
console.trace()
// console.trace()
// (anonymous function)
// InjectedScript._evaluateOn
// InjectedScript._evaluateAndWrap
// InjectedScript.evaluate
console.clear方法用于清除当前控制台的所有输出,将光标回置到第一行。