欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js比较两个单独的数组或对象是否相等的实例代码

程序员文章站 2023-10-30 14:35:22
所谓js的中的传值,其实也就是说5种基本数据类型(null,undefind,boolean,number,string) 传引用也就是说的那个引用数据类型,(array...

所谓js的中的传值,其实也就是说5种基本数据类型(null,undefind,boolean,number,string)

传引用也就是说的那个引用数据类型,(array和object)

基本数据类型的值不可变,而引用数据类型的值是可变的

所以当你比较数组和对象时,都是false;除非你是克隆的原份数据

即: var a = { name: "李四" }; var b = a;

大家通常称对象为引用类型,以此来和基本类型进行区分; 而对象值都是引用,所以的对象的比较也叫引用的比较,当且当他们都指向同一个引用时,即都引用的同一个基对象时,它们才相等.

1.比较两个单独的数组是否相等

json.stringify(a1) == json.stringify(a2)

a1.tostring() == a2.tostring()

要判断2个数组是否相同,把数组转换成字符串进行比较。

如果要比较两个数组的元素是否相等,则:

json.stringify([1,2,3].sort()) === json.stringify([3,2,1].sort());

[1,2,3].sort().tostring() === [3,2,1].sort().tostring();

判断2个数组是否相同,首先要把数组进行排序,然后转换成字符串进行比较。

2.比较两个单独的对象是否相等

let cmp = ( 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 be objects
 if ( ! ( x instanceof object ) || ! ( y instanceof object ) ) {
  return false;
 }
//they must have the exact same prototype chain,the closest we can do is
//test the constructor.
 if ( x.constructor !== y.constructor ) {
  return false;
 }
 for ( var p in x ) {
  //inherited properties were tested using x.constructor === y.constructor
  if ( x.hasownproperty( p ) ) {
  // allows comparing x[ p ] and y[ p ] when set to undefined
  if ( ! y.hasownproperty( p ) ) {
   return false;
  }
  // 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 false;
  }
  // objects and arrays must be tested recursively
  if ( ! object.equals( x[ p ], y[ p ] ) ) {
   return false;
  }
  }
 }
 for ( p in y ) {
  // allows x[ p ] to be set to undefined
  if ( y.hasownproperty( p ) && ! x.hasownproperty( p ) ) {
  return false;
  }
 }
 return true;
};

下面是*大神封装的方法,可以学习一下:

1.比较数组

// warn if overriding existing method
if(array.prototype.equals)
 console.warn("overriding existing array.prototype.equals. possible causes: new api defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to array's prototype to call it on any array
array.prototype.equals = function (array) {
 // if the other array is a falsy value, return
 if (!array)
  return false;

 // compare lengths - can save a lot of time 
 if (this.length != array.length)
  return false;

 for (var i = 0, l = this.length; i < l; i++) {
  // check if we have nested arrays
  if (this[i] instanceof array && array[i] instanceof array) {
   // recurse into the nested arrays
   if (!this[i].equals(array[i]))
    return false;  
  }   
  else if (this[i] != array[i]) { 
   // warning - two different object instances will never be equal: {x:20} != {x:20}
   return false; 
  }   
 }  
 return true;
}
// hide method from for-in loops
object.defineproperty(array.prototype, "equals", {enumerable: false});

2.比较对象

object.prototype.equals = function(object2) {
  //for the first loop, we only check for types
  for (propname in this) {
    //check for inherited methods and properties - like .equals itself
    //https://developer.mozilla.org/en-us/docs/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 instances anyway, there may be a property that only exists in object2
      //i wonder, if remembering the checked values from the first loop would be 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, do not check any more (it must be equa if both objects inherit it)
    if(!this.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 false;
    }
    else if (this[propname] instanceof object && object2[propname] instanceof object) {
          // recurse into another objects
          //console.log("recursing to compare ", this[propname],"with",object2[propname], " 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;
}

总结

以上所述是小编给大家介绍的js比较两个单独的数组或对象是否相等的实例代码,希望对大家有所帮助