您的位置:首页 > Web前端 > JavaScript

Javascript对json及array中多余逗号处理

2011-10-12 00:00 260 查看
在Javascript中,如果出现以下代码

var json = {
name: 'jim',
age: 16, //注意,这里多了一个逗号
};

json.toString = function(){
return 'Name:' + this.name + ', Age:' + this.age;
}

console.log(json.toString());


在标准浏览器、IE8+ 中,都能正常的执行,但在IE6、7中,却会报错 。

同样,在array中若是多了一个逗号呢,代码如下:

var animal = ['sheep', 'cat', 'dog',];//同样多了一个逗号
for(var i = 0,length = animal.length; i<=length; i++){
console.log(animal[i]);
}
console.log(animal.length);


IE中不会报错,但是,确会有个很严重的问题。

IE6、7、8中会认为animal.length等于4,其中的元素为 'sheep', 'cat', 'dog', undefined

但标准浏览器和IE9中,忽略最后多余的逗号。 其实,在ECMAScript 5中有所规定,对于json或array中多余的逗号进行忽略处理,但是直到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判断写法,就是应用了IE6~8中的这个bug,但是IE9中这个bug不再存在,这种判断不再适用。

/**
* 这里具体看看,若数组中仅有一个数字元素,-[1]则返回-1
* 但若数组中元素个数大于一个,则返回NaN
* IE6~8 中,[1,]被认为是两个元素,返回了NaN, !NaN == true
* 标准浏览器和IE9中忽略多余逗号,返回-1, !-1 == false
*/
var ie = !-[1,];
alert(ie);


因此,为了代码兼容性,应当注意多余逗号现象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Javascript json array 逗号