Compare two arrays of equal

Source: Internet
Author: User
Tags hasownproperty

Today, it was accidentally discovered that JavaScript cannot be directly compared with the = = or = = = two arrays for equality.

alert ([]==[]);    Falsealert ([]===[]);   False

The above two lines of code will pop up false.

Because the array in JavaScript is an object, the = = or = = = operator can only compare two objects for the same instance, that is, whether it is the same object reference. Currently JavaScript does not have a built-in operator to determine whether the object's content is the same.

But inertial thinking makes people think that arrays are also values that can be compared.

If you want to compare arrays for equality, you can only traverse array element comparisons.

It's a common practice to spread the array into a string:

1 JSON.stringify(a1) == JSON.stringify(a2)

Or

1 a1.toString() == a2.toString()

Please do not use this method.

This method is feasible in some cases, when the elements of the two array are in the same order and the elements can be converted into strings, but such code is hidden, such as the number is converted to a string, the number "1" and the string "1" will be considered equal, it may cause debugging difficulties, not recommended.

The great God in StackOverflow has provided the right method, I will do the porter:

 1//Warn If overriding existing Method 2 if (Array.prototype.equals) 3 Console.warn ("overriding existing Array.protot Ype.equals. Possible causes:new API Defines the method, there ' s a framework conflict or you ' ve got double inclusions in Y Our code. "); 4//Attach the. Equals method to Array's prototype to call it in any Array 5 Array.prototype.equals = function (array) { 6//If the other array is a Falsy value, return 7 if (!array) 8 return false;     9//Compare Lengths-can save a lot of time one if (this.length! = array.length) return false;13 14 for (var i = 0, L = this.length; i < L; i++) {the//Check if we have a nested ARRAYS16 if (This[i] in Stanceof array && array[i] instanceof Array) {//recurse into the nested ARRAYS18 if (!       This[i].equals (Array[i])) return false; All else if (this[i]! = Array[i]) {$//WARNING-TWO different object instances would never be equal: {x:20}! = {x:20}23 return false; From For-in loops29 object.defineproperty (A), true;27}28//Hide method from Rray.prototype, "equals", {enumerable:false});

The great God also gave a way to compare object:

Object.prototype.equals = function (object2) {//for The first loop, we only check for types for (propname on this) { Check for inherited methods and properties-like. Equals itself//https://developer.mozilla.org/en-us/do        Cs/web/javascript/reference/global_objects/object/hasownproperty//return False if the Return value is different        if (This.hasownproperty (propname)! = Object2.hasownproperty (propname)) {return false;  }//check Instance type else if (typeof this[propname]! = typeof Object2[propname]) {//different        types = Not equal return false; }}//now a deeper check using other objects property names for (propname in object2) {//we must check INS Tances Anyway, there may is a property that is only exists in Object2//i wonder, if remembering the checked value s from the first loop would is faster or not if (This.hasownproperty (propname)! = Object2.hasowNproperty (propname)) {return false;        } else if (typeof this[propname]! = typeof Object2[propname]) {return false; }//if the property is inherited, does not check any further (it must be equa if both objects inherit it) if (!thi        S.hasownproperty (propname)) continue; Now the detail check and recursion//this returns the script back to the array comparing/**requires array . equals**/if (This[propname] instanceof array && object2[propname] instanceof Array) {/ /recurse into the nested arrays if (!this[propname].equals (Object2[propname])) return FA        Lse } else if (This[propname] instanceof object && Object2[propname] instanceof object) {// Recurse into another objects//console.log (' recursing to compare ', This[propname], "with", Object2[propna       Me], "both named \" "+propname+" \ "");    if (!this[propname].equals (Object2[propname])) return false;           }//normal value comparison for strings and numbers else if (this[propname]! = Object2[propname]) {        return false;   }}//if everything passed, let ' s say YES return true;}

Compare two arrays of equal

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.