【问题标题】:Object Properties order and JSON.stringify equality [duplicate]对象属性顺序和 JSON.stringify 相等性 [重复]
【发布时间】:2019-01-30 09:00:36
【问题描述】:

基于不保证属性顺序的对象的定义,是否有可能以下返回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"})

【问题讨论】:

    标签: javascript object properties stringify


    【解决方案1】:

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

    【讨论】:

    • 我相信 OP 不是在问这在一种情况下是否正确,而是在所有情况下都可以保证正确。
    • 添加了一个编辑你认为它回答了这个问题吗?
    猜你喜欢
    • 2013-04-16
    • 2017-09-09
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多