根据MDN documentation for JSON.stringify :
Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
我曾希望通过缓存对象的字符串化版本,然后将其与随后的对象字符串化版本进行比较来确定对象是否更改。这似乎比递归地遍历对象并进行比较要简单得多。问题是因为 JSON.stringify 函数不是确定性的,当我对同一个对象进行字符串化时,从技术上讲,我可以得到不同的字符串。
我还有什么其他选择?还是我必须编写一个讨厌的比较函数来确定对象是否相等?
最佳答案
我很确定这是因为不同的 JavaScript 引擎在内部跟踪对象属性的方式。以此为例:
var obj = {
"1" : "test",
"0" : "test 2"
};
for(var key in obj) {
console.log(key);
}
这将记录 1, 0 例如Firefox,但在 V8(Chrome 和 NodeJS)中是 0、1。 因此,如果您需要确定性,您可能必须遍历每个键,将其存储在一个数组中,对数组进行排序,然后通过遍历该数组分别对每个属性进行字符串化。
https://stackoverflow.com/questions/8931967/