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 相关文章推荐
通过JAVASCRIPT读取ASP设定的COOKIE
Nov 24 Javascript
jquery入门必备的基本认识及实例(整理)
Jun 24 Javascript
javascript自然分类法算法实现代码
Oct 11 Javascript
js动态添加事件并可传参数示例代码
Oct 21 Javascript
100个不能错过的实用JS自定义函数
Mar 05 Javascript
javascript动态修改Li节点值的方法
Jan 20 Javascript
使用vue.js2.0 + ElementUI开发后台管理系统详细教程(二)
Jan 21 Javascript
简单介绍react redux的中间件的使用
Apr 06 Javascript
详解基于node.js的脚手架工具开发经历
Jan 28 Javascript
vue 中固定导航栏的实例代码
Nov 01 Javascript
vue使用axios实现excel文件下载的功能
Jul 16 Javascript
js实现全选和全不选功能
Jul 28 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
php学习笔记 PHP面向对象的程序设计
2011/06/13 PHP
PHP安全性漫谈
2012/06/28 PHP
深入phpMyAdmin的安装与配置的详细步骤
2013/05/07 PHP
基于xcache的配置与使用详解
2013/06/18 PHP
php实现图形显示Ip地址的代码及注释
2014/01/20 PHP
PHP学习笔记(三):数据类型转换与常量介绍
2015/04/17 PHP
PHP json_encode() 函数详解及中文乱码问题
2015/11/05 PHP
PHP7 list() 函数修改
2021/03/09 PHP
JS+CSS实现大气的黑色首页导航菜单效果代码
2015/09/10 Javascript
基于JS实现新闻列表无缝向上滚动实例代码
2016/01/22 Javascript
两种JavaScript的AES加密方式(可与Java相互加解密)
2016/08/02 Javascript
jQuery实现联动下拉列表查询框
2017/01/04 Javascript
Web制作验证码功能实例代码
2017/06/19 Javascript
原生JavaScript实现remove()和recover()功能示例
2018/07/24 Javascript
jquery ajax加载数据前台渲染方式 不用for遍历的方法
2018/08/09 jQuery
JavaScript使用递归和循环实现阶乘的实例代码
2018/08/28 Javascript
小程序实现留言板
2018/11/02 Javascript
vue插槽slot的理解和使用方法
2019/04/03 Javascript
elementUI vue this.$confirm 和el-dialog 弹出框 移动 示例demo
2019/07/03 Javascript
layer.open 获取不到表单信息的解决方法
2019/09/26 Javascript
bootstrap实现嵌套模态框的实例代码
2020/01/10 Javascript
JS highcharts动态柱状图原理及实现
2020/10/16 Javascript
vue实现滚动鼠标滚轮切换页面
2020/12/13 Vue.js
利用numpy+matplotlib绘图的基本操作教程
2017/05/03 Python
Python2.7实现多进程下开发多线程示例
2019/05/31 Python
Visual Studio code 配置Python开发环境
2020/09/11 Python
CSS3——齿轮转动关键代码
2013/05/02 HTML / CSS
西班牙国家航空官方网站:Iberia
2017/11/16 全球购物
培训协议书范本
2014/04/22 职场文书
2014统计局民主生活会对照检查材料思想汇报
2014/10/02 职场文书
2014年检验员工作总结
2014/11/19 职场文书
2015年财务经理工作总结
2015/05/13 职场文书
初婚初育证明范本
2015/06/18 职场文书
2016党员干部廉政准则学习心得体会
2016/01/20 职场文书
祝福语集锦:给妹妹结婚的祝福语
2019/12/18 职场文书
python playwright 自动等待和断言详解
2021/11/27 Python