首页 > 解决方案 > 对象属性顺序和 JSON.stringify 相等

问题描述

根据不保证属性顺序的对象的定义,以下是否有可能返回false?

JSON.stringify({a: "A", b: "B"}) == JSON.stringify({a: "A", b: "B"})

更新:当然,我在控制台中尝试过,我总是正确的,但这与不能保证属性顺序的事实背道而驰。我不确定我是否理解属性的顺序在什么时候与声明时的顺序不同。

以下也证明了属性的顺序保持不变:

example = {}
example.a = "A"
example.c = "C"
example.b = "B"

JSON.stringify(example) == JSON.stringify({a: "A", c: "C", b: "B"})

标签: javascriptobjectpropertiesstringify

解决方案


JSON.stringify()返回一个字符串,因此如果属性的顺序发生变化,则返回的字符串会发生变化。

去尝试一下。

console.log(JSON.stringify({a: "A", b: "B"}) == JSON.stringify({a: "A", b: "B"}));
console.log(JSON.stringify({a: "A", b: "B"}) == JSON.stringify({b: "B", a: "A"}));


推荐阅读