欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Chrome处理JSON数据时的特殊之处 博客分类: web前端 Chromejson 

程序员文章站 2024-03-23 17:16:46
...

有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得到结果均为:

ID:2,Name:shanghai
ID:1,Name:beijing
ID:4,Name:shenzhen
ID:3,Name:xianggang

 但Chrome的运行结果为:

 

ID:1,Name:beijing
ID:2,Name:shanghai
ID:3,Name:xianggang
ID:4,Name:shenzhen

 原因在于这个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>

 则各浏览器下结果均为:

 

ID:2,Name:shanghai
ID:1,Name:beijing
ID:4,Name:shenzhen
ID:3,Name:xianggang
 

 

相关标签: Chrome json