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

 更新时间:2019年04月28日 08:33:41   作者:消逝的风i  
本文通过实例代码给大家介绍了js比较两个单独的数组或对象是否相等 ,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

所谓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;
};

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

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比较两个单独的数组或对象是否相等的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

  • JavaScript中的细节分析

    JavaScript中的细节分析

    高山登不上,不是因为体力不支,只因鞋里一粒。学习也是如此,因而有必要把JavaScript中常见的和与其它语言不同的那些细节学习一下
    2012-06-06
  • JavaScript function 的 length 属性使用介绍

    JavaScript function 的 length 属性使用介绍

    函数的 length 得到的是形参个数,如果函数内部是通过arguments 调用参数,而没有实际定义参数的话, length 只会的得到0
    2014-09-09
  • uniapp单页面实现页面切换的使用示例

    uniapp单页面实现页面切换的使用示例

    本文主要介绍了uniapp单页面实现页面切换的使用示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-09-09
  • 详解JavaScript作用域、作用域链和闭包的用法

    详解JavaScript作用域、作用域链和闭包的用法

    这篇文章主要介绍了JavaScript作用域、作用域链和闭包的用法,帮助大家更好的理解和使用JavaScript,感兴趣的朋友可以了解下
    2020-09-09
  • js读取注册表的键值示例

    js读取注册表的键值示例

    读取注册表的键值的方法有很多,在本文将为大家详细介绍下使用js如何实现注册表的键值读取,感兴趣的朋友可以参考下
    2013-09-09
  • cropper js基于vue的图片裁剪上传功能的实现代码

    cropper js基于vue的图片裁剪上传功能的实现代码

    这篇文章主要介绍了cropper js基于vue的图片裁剪上传功能的相关资料,需要的朋友可以参考下
    2018-03-03
  • Layer弹出层动态获取数据的方法

    Layer弹出层动态获取数据的方法

    今天小编就为大家分享一篇Layer弹出层动态获取数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • 简单实现js浮动框

    简单实现js浮动框

    这篇文章主要为大家详细介绍了如何简单实现js浮动框,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-12-12
  • javascript中的parseInt和parseFloat区别

    javascript中的parseInt和parseFloat区别

    这篇文章用简单的小例子演示了parseInt和parseFloat区别,有需要的朋友可以参考一下
    2013-07-07
  • 微信小程序h5页面跳转小程序的超详细讲解

    微信小程序h5页面跳转小程序的超详细讲解

    开发中涉及到一个需求,就是从一个预约票购买的页面需要跳转到 小程序,下面这篇文章主要给大家介绍了关于微信小程序h5页面跳转小程序的超详细讲解,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-02-02

最新评论