由于JavaScript中无法保证对象中的属性顺序,因此JSON.stringify()实际上如何表现? [英] Since properties order in objects is not guaranteed in JavaScript, how does JSON.stringify() actually behave?

查看:762
本文介绍了由于JavaScript中无法保证对象中的属性顺序,因此JSON.stringify()实际上如何表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 无法保证对象中的属性顺序, JSON.stringify()实际上表现如何?

Since properties order in objects is not guaranteed in JavaScript, how does JSON.stringify() actually behave?


  1. 以下是否始终为真(同一个对象)?

const o = { a: 1, b: 2 };
console.log(JSON.stringify(o) === JSON.stringify(o));


  1. 以下是否始终为真(深度相等的对象,相同的密钥声明顺序)?

console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ a: 1, b: 2 }));


  1. 如何使以下内容成立(深度相等的对象,不同的密钥声明顺序)?

console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 }));

推荐答案

我看了看 JSON.stringify 的ECMAScript标准: http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3

I looked at the ECMAScript standard for JSON.stringify: http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3

这似乎提供了丰富的信息:

This seems informative:


对于K的每个元素P.

For each element P of K.

Let strP be the result of calling the abstract operation Str with arguments P and value.
If strP is not undefined
    Let member be the result of calling the abstract operation Quote with argument P.
    Let member be the concatenation of member and the colon character.
    If gap is not the empty String
        Let member be the concatenation of member and the space character.
    Let member be the concatenation of member and strP.
    Append member to partial.


最后一步中的追加强烈暗示结果按源排序,我可以确认你的代码断言是否传递给Chromium和Firefox。

The "append" in the final step strongly implies that the results are ordered per the source, and I can confirm your code assertions pass on both Chromium and Firefox.

编辑:对于P of K ,这也可能是相关的:

For "P of K", this might be relevant too:


字符串的排序应与Object.keys标准内置的排序相同函数。

The ordering of the Strings should be the same as that used by the Object.keys standard built-in function.

只要比较保存在一个浏览器中,您的断言似乎都是正确的。

It seems that your assertions are true so long as the comparisons are kept in one browser.

这篇关于由于JavaScript中无法保证对象中的属性顺序,因此JSON.stringify()实际上如何表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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