javascript返回两个对象之间的差异

时间:2011-12-02 02:34:36

标签: javascript jquery

我有一个看起来像这样的对象:

var MyObject = {
prop1 = 12345,
prop2 = "string1",
ListOfOtherObject = an array of another type of object,
ListOfAnotherObject = an array of objects}

假设我有两个对象:Object1和Object2。 Object2最初是Object1的深层副本,它通过用户与UI的交互进行了修改。我希望得到两个对象之间的区别,特别是当涉及到数组时。

例如,Object2中的ListOfOtherObject可能包含某些对象的修改版本以及新对象。

我正在考虑循环遍历每个数组,然后循环遍历每个对象,但可能有一些更有效的方法来实现它,尤其是使用jquery。或者可以使用JSON.stringify并比较字符串并返回某种字符串差异。我想知道是否有人对如何做到这一点有任何建议。

感谢。

1 个答案:

答案 0 :(得分:1)

您需要指定比较需要执行的操作。例如,给定:

var o = {name: 'fred'};
var p = {name: 'fred'};
var a = {o:o};
var b = {o:o};

然后:

a == b;     // false, a and b are different objects
a.o == b.o; // true since a.o and b.o reference the same object

但是如果比较对象:

b.o = p;
a.o == b.o; // false since a.o and b.o reference different objects

或者如果比较原语:

a.o.name == b.o.name; // true since the value of both expressions is the string 'fred'
                      // even though a.o and b.o are different objects

Type或构造函数是否重要?怎么样:

b.o = [];
b.o.name = 'fred';

a.o.name == b.o.name;  // true or false? a.o is an object, b.o is an array