【发布时间】:2018-03-08 17:58:24
【问题描述】:
由于properties order in objects is not guaranteed in JavaScript,JSON.stringify() 的实际表现如何?
- 以下是否总是正确的(同一个对象)?
const o = { a: 1, b: 2 };
console.log(JSON.stringify(o) === JSON.stringify(o));
- 以下是否总是正确的(深度相等的对象,相同的键声明顺序)?
console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ a: 1, b: 2 }));
- 如何使以下为真(深度相等的对象,不同的键声明顺序)?
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