由于 JavaScript 中不保证对象中的属性顺序,JSON.stringify() 的实际行为如何?

2023-11-29

Since JavaScript 中不保证对象中的属性顺序, 如何JSON.stringify()实际上表现如何?

  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 }));

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

这看起来信息丰富:

对于 K 的每个元素 P。

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 上都通过了。

EDIT:对于“P of K”,这也可能相关:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

由于 JavaScript 中不保证对象中的属性顺序,JSON.stringify() 的实际行为如何? 的相关文章