使用JSON.stringify进行深度比较和克隆是否合适? [英] Is it fine to use JSON.stringify for deep comparisons and cloning?

查看:201
本文介绍了使用JSON.stringify进行深度比较和克隆是否合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试了几种实现方式以进行深度比较并复制可序列化的JSON对象后,我注意到最快的往往是:

After attempting several implementations for deep comparison and copying for JSON-serializable objects, I've noticed the fastest often are just:

function deep_clone(a){
   return JSON.parse(JSON.stringify(a));
};
function is_equal(a,b){
    return JSON.stringify(a) === JSON.stringify(b);
};

不过我觉得这是作弊。就像我会发现一些困扰我未来的问题。

I feel like this is cheating, though. Like I'll find some problem that will annoy me on future. Is it fine to use those?

推荐答案

JavaScript不保证键的顺序。

JavaScript does not guarantee the order of keys.

如果以相同的顺序输入它们,这种方法在大多数情况下都可以使用,但是并不可靠。

If they are entered in the same order, this approach would work most of the time, but it would not be reliable.

此外,对于高度相等但以不同顺序输入其键的对象,返回false:

Also, it would return false for objects that were deeply equal, but whose keys were entered in a different order:

JSON.stringify({ a: 1, b: 2}) === "{"a":1,"b":2}"

JSON.stringify({ b: 2, a: 1}) === "{"b":2,"a":1}"

这篇关于使用JSON.stringify进行深度比较和克隆是否合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆