JavaScript compares two objects for equality _javascript tips

Source: Internet
Author: User
Tags hasownproperty in python

The example in this article tells you how JavaScript compares two objects for equality. Share to everyone for your reference. Specifically as follows:

In Python, you can use the CMP () built-in function to compare two objects for equality (arrays, sequences, dictionaries). However, there is no relevant implementation in the JavaScript language. This JS code by the JS object in various aspects of the comparison to determine whether two objects are equal

CMP = function (x, y) {//If both x and y are null or undefined and exactly the same If (x = = y) {return true; }//If they are not strictly equal, they both-need to IS Objects If (! (x instanceof Object) | | ! (y instanceof Object)) 
{return false; 
}//they must have the exact same prototype chain,the we can do are closest the//test. 
if (x.constructor!== y.constructor) {return false; For (var p in x) {//inherited properties were tested using X.constructor = = Y.constructor if (x.hasownpropert Y (P)) {//allows comparing x[p] and y[p] When set to undefined if (! Y.hasownproperty (p)) {return fals 
 E 
 }//If they have the same strict value or identity then they-are equal If (x[p] = = y[P]) {continue; }//Numbers, Strings, functions, booleans must be strictly equal if (typeof (X[p])!== "Object") {return FA 
 Lse }//Objects and Arrays must be tested recursively if (! Object.Equals (x[p], y[p]) {return false; (p in Y) {//allows x[P] to is set to undefined if (Y.hasownproperty (p) &&! X.HASOWNPR 
 Operty (p)) {return false; 
} return true; };

Use:

obja={ 
 A: ' 123 ', 
 B: ' 456 ' 
}; 
objb={ 
 A: ' 123 ', 
 B: ' 
}; 
var isequal= cmp (Obja, OBJB); 
 Console.log (isequal);  False is not the same

I hope this article will help you with your JavaScript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.