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


Posted in Javascript onApril 28, 2019

所谓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 相关文章推荐
js限制文本框为整数和货币的函数代码
Oct 13 Javascript
jQuery基本选择器选择元素使用介绍
Apr 18 Javascript
javascript数组操作总结和属性、方法介绍
Apr 05 Javascript
推荐8款jQuery轻量级树形Tree插件
Nov 12 Javascript
Javascript实现Web颜色值转换
Feb 05 Javascript
JavaScript实现控制打开文件另存为对话框的方法
Apr 17 Javascript
防止重复发送 Ajax 请求
Feb 15 Javascript
js面向对象编程总结
Feb 16 Javascript
js中new一个对象的过程
Feb 20 Javascript
js上下视差滚动简单实现代码
Mar 07 Javascript
利用Vue构造器创建Form组件的通用解决方法
Dec 03 Javascript
JavaScript基于SVG的图片切换效果实例代码
Dec 15 Javascript
详解在HTTPS 项目中使用百度地图 API
Apr 26 #Javascript
vue操作动画的记录animate.css实例代码
Apr 26 #Javascript
JS原生瀑布流效果实现
Apr 26 #Javascript
Vue基于vuex、axios拦截器实现loading效果及axios的安装配置
Apr 26 #Javascript
详解auto-vue-file:一个自动创建vue组件的包
Apr 26 #Javascript
vue组件间的参数传递实例详解
Apr 26 #Javascript
详解VUE前端按钮权限控制
Apr 26 #Javascript
You might like
destoon实现首页显示供应、企业、资讯条数的方法
2014/07/15 PHP
php+mysqli预处理技术实现添加、修改及删除多条数据的方法
2015/01/30 PHP
Yii2下session跨域名共存的解决方案
2017/02/04 PHP
PHP 实现从数据库导出到.csv文件方法
2017/07/06 PHP
PHP中的访问修饰符简单比较
2019/02/02 PHP
jQuery代码优化之基本事件
2011/11/01 Javascript
JavaScript获取网页表单action属性的方法
2015/04/02 Javascript
学习javascript的闭包,原型,和匿名函数之旅
2015/10/18 Javascript
JS实现加载和读取XML文件的方法详解
2017/04/24 Javascript
angularjs封装$http为factory的方法
2017/05/18 Javascript
vue2中filter()的实现代码
2017/07/09 Javascript
Three.js利用dat.GUI如何简化试验流程详解
2017/09/26 Javascript
解决axios会发送两次请求,有个OPTIONS请求的问题
2018/10/25 Javascript
微信小程序制作表格的方法
2019/02/14 Javascript
JS实现根据详细地址获取经纬度功能示例
2019/04/16 Javascript
uni-app如何实现增量更新功能
2020/01/03 Javascript
VSCode搭建React Native环境
2020/05/07 Javascript
绘制微信小程序验证码功能的实例代码
2021/01/05 Javascript
python在Windows下安装setuptools(easy_install工具)步骤详解
2016/07/01 Python
Python反转序列的方法实例分析
2018/03/21 Python
python3实现基于用户的协同过滤
2018/05/31 Python
Win8下python3.5.1安装教程
2020/07/29 Python
python求最大值最小值方法总结
2019/06/25 Python
CSS3实现类似翻书效果的过渡动画的示例代码
2019/09/06 HTML / CSS
Magee 1866官网:Donegal粗花呢外套和大衣专家
2019/11/01 全球购物
易程科技软件测试笔试
2013/03/24 面试题
物流专业求职计划书
2014/01/10 职场文书
单位消防安全制度
2014/01/12 职场文书
献爱心倡议书
2014/04/14 职场文书
好习惯伴我成长演讲稿
2014/05/21 职场文书
娱乐节目策划方案
2014/06/10 职场文书
法学专业毕业生自荐信
2014/06/11 职场文书
我的中国梦演讲稿高中篇
2014/08/19 职场文书
市场营销计划书
2015/01/17 职场文书
深入理解CSS 中 transform matrix矩阵变换问题
2021/08/30 HTML / CSS
python中的random模块和相关函数详解
2022/04/22 Python