Javascript对json及array中多余逗号处理
2011-10-12 00:00
260 查看
在Javascript中,如果出现以下代码
在标准浏览器、IE8+ 中,都能正常的执行,但在IE6、7中,却会报错 。
同样,在array中若是多了一个逗号呢,代码如下:
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不再存在,这种判断不再适用。
因此,为了代码兼容性,应当注意多余逗号现象。
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);
因此,为了代码兼容性,应当注意多余逗号现象。
相关文章推荐
- js定义对象或数组直接量时各浏览器对多余逗号的处理(json)
- js定义对象或数组直接量时各浏览器对多余逗号的处理(json)
- ajax传回的json对象要用javascript中的eval()函数处理的原因
- JSON学习(二) - JavaScript处理JSON数据
- JavaScript处理Json
- PHP的array转为Json并转化为Javascript对象
- Javascript中的Array(数组) 、{}(映射) 与JSON解析
- javascript 处理json相关
- javascript如何处理/接收URL中的Json数据?
- JavaScript 处理 JSON 数据
- 【脚本语言系列】关于 JavaScript JSON处理,你需要知道的事
- 关于PHP处理JAVA过来的接口和PHP返回给Javascript的JSON字符串
- JavaScript eval处理JSON数据 为什么要加括号
- javascript处理json
- json-lib使用,JSONObject和JSONArray---js处理json
- [转载]EXT核心API详解Ext.data(十)-DataReader/ArrayReader/JsonReader/XmlReader javascript
- 将JSON字符串处理成javascript可以识别的
- js中jsonArray的封装处理
- JavaScript如何处理解析JSON数据详解
- 用 javascript 处理 JSON