日期:2014-05-16 浏览次数:20334 次
有JSON字符串如下:
?
var cities = { "2": { "id":"2","name":"shanghai" }, "1": { "id":"1","name":"beijing" }, "4": { "id":"4","name":"shenzhen" }, "3": { "id":"3","name":"xianggang" } };
?
?遍历该JSON对象,将其顺序打印出来,Chrome会和其他浏览器得到不同的结果。
?
<script> var cities = { "2": { "id":"2","name":"shanghai" }, "1": { "id":"1","name":"beijing" }, "4": { "id":"4","name":"shenzhen" }, "3": { "id":"3","name":"xianggang" } }; var row; for(i in cities) { row = "ID:"+cities[i].id+",Name:"+cities[i].name+"<br />"; document.write(row); } </script>
?
?IE、Firefox及Safari得到结果均为:
?但Chrome的运行结果为:
?
?原因在于这个JSON对象下标是数字,Chrome根据其下标由小到大对对象个元素重新排了序。
?若把下标改为字符或者将下标删除:
?
<script> /* var cities = { "b": { "id":"2","name":"shanghai" }, "a": { "id":"1","name":"beijing" }, "d": { "id":"4","name":"shenzhen" }, "c": { "id":"3","name":"xianggang" } }; */ var cities = [ { "id":"2","name":"shanghai" }, { "id":"1","name":"beijing" }, { "id":"4","name":"shenzhen" }, { "id":"3","name":"xianggang" } ]; var row; for(i in cities) { row = "ID:"+cities[i].id+",Name:"+cities[i].name+"<br />"; document.write(row); } </script>
?则各浏览器下结果均为:
?
?