zoukankan      html  css  js  c++  java
  • 定义对象或数组直接量时不同引擎对多余逗号的处理

    这种错误已经多次犯了,一次用Ext做abcc的demo,一次是abcc查询模块。
    js报错分为两种:语法错误和运行错误

    1、js引擎在代码载入时进行语法分析,如果js写的不规范则语法分析通不过。这时候的错误称为语法错误
    2、语法分析通过了,js引擎会执行代码。执行期间发生的错误称为运行错误

    不同引擎处理这2种错误的提示不太一样。如下:

    var p = {name:"Jack",age:33,};//注意33后有个逗号
        p.toString = function() {return "姓名:" +this.name + ",年龄:" + this.age};
    console.log(p);
    alert(p);//姓名:Jack,年龄33

    firefox下测试,引擎会忽略33后的逗号,可以通过语法检查,在执行期也不会报错
    IE6/7下测试,语法分析期就报错了,当然也不会进入执行期了。
    不过在IE8下已经修复此问题,不会报错了。其它浏览器也不会报错。

    总结下:此错误很难发现,经常是不小心就加了个逗号,或者定义了一个很多属性的对象或数组后来又要删除其中的某些而不小心留下了多余的逗号。

    //不规范的写法
    var p = {name:"Jack",age:33,};
    var ary = ["one","two","three",];
    //规范的写法
    var p = {name:"Jack",age:33};
    var ary = ["one","two","three"];
    

    此外,定义数组直接量时也可能碰到这个问题,如数组最后多了个逗号

    var ary = [1,2,];
    console.log(ary.length);
    

    IE6/7/8 输出length为3,IE9及其它浏览器为2。ECMAScript 5 11.1.4 其中有段说明了应该忽略最后的逗号。但直到IE9才实现该规范。其它浏览器则没问题。

    ECMAScript 5 11.1.4 写道:

    Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

    有人曾经利用了数组的这个特性创造出了所谓《全世界最短的IE判断

    var ie = !-[1,]; 
    alert(ie); 

    但在IE9下被终止了。不要利用这个Bug去判断浏览器。

  • 相关阅读:
    Oracle Database 11g : SQL 基础
    Idea-Java接入银联支付的Demo
    Linux文件系统挂载管理
    Linux文件系统
    使用fdisk进行磁盘管理
    Vim文本编辑器
    Linux系统常用命令
    Linux系统目录架构
    Linux文件基本操作管理
    Linux文件系统的基本结构
  • 原文地址:https://www.cnblogs.com/snandy/p/1966221.html
Copyright © 2011-2022 走看看