目录
三、为什么 alert() 和 console.log() 方法打印同样的代码有时结果会不同呢?
一、alert() 方法
- alert() 方法有阻塞作用,不点击确定,后续代码无法继续执行;
- alert() 方法只能输出字符串,如果 alert() 方法输出的是别的值,会自动调用toString()方法将其转为字符串输出;
alert([1,2,3]); // '1,2,3'
- alert() 方法不支持多个参数的写法,只能输出第一个值。
alert(1,2,3); // 1
二、console.log() 方法
- console.log() 方法会在打印控制台输出结果;
- console.log() 方法可以打印任何类型的数据;
- console.log() 方法支持多个参数的写法;
console.log(1,2,3); // 1 2 3
console.log([1,2], [11, 22]); // [1,2] [11,22]
三、为什么 alert() 和 console.log() 方法打印同样的代码有时结果会不同呢?
console.log(1, 2, 3); // 1 2 3
alert(1, 2, 3); // 1
上述代码,结果如此的原因在于: alert() 方法不支持多个参数的写法,只能输出第一个值;console.log() 方法支持多个参数的写法。
function compare(a, b) {
return b - a;
}
var arr = [1,3,6,4,2,5];
arr.sort(compare)
console.log(arr); // [6, 5, 4, 3, 2, 1]
alert(arr); // 6,5,4,3,2,1
上述代码,结果如此的原因在于:alert() 方法只能输出字符串,如果 alert() 方法输出的是别的值,会自动调用toString()方法将其转为字符串输出;方法可以打印任何类型的数据。