javascript的alert()与console.log()

1、我们在做js调试的时候使用 alert 可以显示信息,调试程序,alert 弹出窗口会中断程序, 如果要在循环中显示信息,手点击关闭窗口都累死。而且 alert 显示对象永远显示为[object ]。 自己写的 log 虽然可以显示一些 object 信息,但很多功能支持都没有 console 好

[1]alert()

    [1.1]有阻塞作用,不点击确定,后续代码无法继续执行

    [1.2]alert()只能输出string,如果alert输出的是对象会自动调用toString()方法

        e.g. alert([1,2,3]);//'1,2,3'

    [1.3]alert不支持多个参数的写法,只能输出第一个值

        e.g. alert(1,2,3);//1

[2]console.log()

    [2.1]在打印台输出

    [2.2]可以打印任何类型的数据

        e.g. console.log([1,2,3]);//[1,2,3]

    [2.3]支持多个参数的写法

        e.g. console.log(1,2,3)// 1 2 3

alert 和 console.log 的结果不同?

1
2
3
4
5
6
7
8
score = [1,2,3];
sortedScore = [];
console.log(score);
sortedScore = score.sort(sortNumber)
console.log(sortedScore);
function sortNumber(a, b) {
   return b - a;
}

  

以上输出:
[3, 2, 1]
[3, 2, 1]

但是改成alert:

1
2
3
4
5
6
7
8
score = [1,2,3];
sortedScore = [];
alert(score);
sortedScore = score.sort(sortNumber)
alert(sortedScore);
function sortNumber(a, b) {
   return b - a;
}

  


以上输出:
1, 2, 3
3, 2, 1

为什么会这样?不应该都是:
1, 2, 3
3, 2, 1
吗?

经过一番研究发现是chrome实现的问题,对输出做了不太合适的优化,把console.log的实际执行推迟,相当于“惰性”求值,遇上数组、对象这样的引用类型就出上面的问题了。



2、如何避免console.log()引起的浏览器兼容性问题
简而言之,并不是所有浏览器都能很好的支持这一特性( ie9 以下的版本的浏览器直接报告页面上有错误)。所以,如果我们要广泛的使用 Console 的特征功能,我们要对该对象进行包装,至少不能让他报错吗。
解决方法(可使用下面的代码):
// 不让浏览器报错
var console=console||{log:function(){return;}}
// HTML5 Boilerplate 也提供了一个处理所有的 Console call 的 fallback:
// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});
    while (length--) {
        method = methods[length];
        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());
// Place any jQuery/helper plugins in here.
这样,就可以使得我们的代码在不支持控制台的浏览器中使用 Console 对象的时候不至于报错。追求完美的路是没有终点的——因此,当浏览器不支持 Console 的时候,我们代为浏览器实现 Console ,这样岂不是很妙?其中,具体的实现可以参考 Complete cross-browser console.log() 一文。



 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值