Comparing two objects in JavaScript is not a simple task, and it does not provide such an API. If you want to use the & quot; operator to compare two objects, it is a big mistake. Comparing two objects in JavaScript is not a simple task, and it does not provide such an API.
If you want to use the "=" operator to compare two objects, it is a big mistake.
The "=" operator returns true only when the variables on both sides point to the same object.
For example, in the following example, false is returned.
var a = { name: 'Joe' }; var b = { name: 'Joe' }; a == b; //-> false
So what are the criteria for comparing two objects?
1. Do they have the same attribute name?
2. Do they have the same attribute values?
For example, for the objects a and B above, both of them have "name" attribute names and have "Joe" attribute values. Therefore, they are "similar ".
In other words, our purpose is to determine whether two JS objects are "similar ".
The above two objects are very simple. If we encounter nested objects, it will become complicated.
Because there are many types of objects, such as regular objects, function objects, and date objects, comparing them will increase the complexity of the program. Therefore, we only consider the following situations: common Object ({}), array object ([]), and basic simple type (string, number, boolean, null, undefined ).
Even if the requirement is simplified, it is not easy to accomplish this comparison. In the following example, I used the in-depth traversal object to compare the attribute names and values of the object one by one.
Function deepCompare (o1, o2) {// identify whether it is similar to var flag = true; var traverse = function (o1, o2) {// if at least one is not an object if (! (O1 instanceof Object) |! (O2 instanceof Object) {if (o1! = O2) {flag = false;} return;} // If the attribute quantity of the two objects is inconsistent, // For example: // a: {name: "Jack", age: 22} // B: {name: "Jack"} if (Object. keys (o1 ). length! = Object. keys (o2 ). length) {flag = false;} // if there are any differences, end the recursion if (flag) as early as possible {// traverse the object in depth for (var I in o1) {// if all objects are objects, continue recursion if (typeof o1 [I] = "object" & typeof o2 [I] = "object ") {traverse (o1 [I], o2 [I]);} // if none of them are objects, compare the else if (typeof o1 [I]! = "Object" & typeof o2 [I]! = "Object") {if (o1 [I]! = O2 [I]) {flag = false ;}// one is an object, and the other is not an object. It is certainly not similar to else {flag = false ;}}}}; traverse (o1, o2); return flag ;};
The above is the JavaScript interesting question: the content of the object for deep comparison. For more information, please follow the PHP Chinese Network (www.php1.cn )!