【问题标题】:Since properties order in objects is not guaranteed in JavaScript, how does JSON.stringify() actually behave?由于 JavaScript 不保证对象中的属性顺序,因此 JSON.stringify() 的实际行为如何?
【发布时间】:2018-03-08 17:58:24
【问题描述】:

由于properties order in objects is not guaranteed in JavaScriptJSON.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 }));

【问题讨论】:

  • 1) 是的,同一对象上的枚举顺序始终保证相同。 2)它应该是,虽然没有严格的保证我们会期待确定性。 3)你不能“使”这件事成真,你应该只使用a deep equality predicate function而不是比较JSON.stringify结果

标签: javascript json object serialization idempotent


【解决方案1】:

我查看了JSON.stringify 的 ECMAScript 标准: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 上都通过了。

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

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

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

【讨论】:

  • 没有。追加意味着字符串是按照“对于 K 的每个元素 P”的顺序构建的,这并不意味着它们是按源排序的(或者对于动态生成的对象可能是什么)。
猜你喜欢
  • 2017-09-09
  • 2021-11-20
相关资源
最近更新 更多