JSON.stringify是否保留数组中对象的顺序 [英] Does JSON.stringify preserves order of objects in array

查看:476
本文介绍了JSON.stringify是否保留数组中对象的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个javascript对象,如下所示

I am creating a javascript object as follows

var myObjects ; 
for(var i = 0; i <10;i++){
    var eachObject = {"id" : i};
    myObjects .push(eachObject );
}
message = {
      "employeeDetails" : myObjects 
}

在此之后我将它们按如下方式字符串化

After this I stringify them as follows

JSON.stringify(message);

上述方法是否按照先前的顺序对对象进行字符串化?
在stringify之后,它们将按照先前的顺序为0,1,2 .... 9?

Does the above method stringifies the objects in the order they were previously? After stringify will they be in the order 0,1,2....9 as they were previously?

推荐答案

文档中没有任何内容明确确认数组项的顺序是保留的。但是,文档声明对于非数组属性,不保证顺序:

There is nothing in the docs that explicitly confirms that the order of array items is preserved. However, the docs state that for non-array properties, order is not guaranteed:


不保证非数组对象的属性按任何特定顺序进行字符串化。不要依赖于字符串化内同一对象内的属性排序。

Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects / JSON / stringify

即使数组项的顺序会被保留,我也不会指望这一点,而是自己对项目进行排序。毕竟,很可能会有一些业务或表示逻辑指示如何对项目进行排序。

Even if the order of array items would be preserved, I would not count on this but rather sort the items myself. After all, there will most likely be some business or presentation logic that indicates how the items should be sorted.

这篇关于JSON.stringify是否保留数组中对象的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆