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 相关文章推荐
探讨jQuery的ajax使用场景(c#)
Dec 03 Javascript
用Jquery实现滚动新闻
Feb 12 Javascript
JQuery.Ajax()的data参数类型实例详解
Nov 20 Javascript
Js获取图片原始宽高的实现代码
May 17 Javascript
详解Node.js:events事件模块
Nov 24 Javascript
JS实现问卷星自动填问卷脚本并在两秒自动提交功能
Jun 17 Javascript
Three.js如何用轨迹球插件(trackball)增加对模型的交互功能详解
Sep 25 Javascript
JavaScript中Require调用js的实例分享
Oct 27 Javascript
vue中子组件向父组件传递数据的实例代码(实现加减功能)
Apr 20 Javascript
原生JS实现相邻月份日历
Oct 13 Javascript
JS绘图Flot如何实现动态可刷新曲线图
Oct 16 Javascript
Vue过滤器(filter)实现及应用场景详解
Jun 15 Vue.js
详解在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 5.0 Pear安装方法
2006/12/06 PHP
php+mysql开源XNA 聚合程序发布 下载
2007/07/13 PHP
php中的注释、变量、数组、常量、函数应用介绍
2012/11/16 PHP
解析php函数method_exists()与is_callable()的区别
2013/06/21 PHP
如何使用php输出时间格式
2013/08/31 PHP
php强制文件下载而非在浏览器打开的自定义函数分享
2014/05/08 PHP
总结PHP中初始化空数组的最佳方法
2019/02/13 PHP
PHP正则验证字符串是否为数字的两种方法并附常用正则
2019/02/27 PHP
jQuery实现列表自动循环滚动鼠标悬停时停止滚动
2013/09/06 Javascript
jquery与js函数冲突的两种解决方法
2013/09/09 Javascript
深入理解JSON数据源格式
2014/01/10 Javascript
自己封装的javascript事件队列函数版
2014/06/12 Javascript
jquery实现在页面加载的时自动为日期插件添加当前日期
2014/08/20 Javascript
easyUI combobox实现联动效果
2017/01/17 Javascript
利用js判断手机是否安装某个app的多种方案
2017/02/13 Javascript
angularjs封装$http为factory的方法
2017/05/18 Javascript
webpack构建vue项目的详细教程(配置篇)
2017/07/17 Javascript
解决vue中使用swiper插件问题及swiper在vue中的用法
2018/04/04 Javascript
微信小程序实现默认第一个选中变色效果
2018/07/17 Javascript
vue自定义指令directive的使用方法
2019/04/07 Javascript
微信小程序 动态修改页面数据及参数传递过程详解
2019/09/27 Javascript
React组件设计模式之组合组件应用实例分析
2020/04/29 Javascript
[56:12]LGD vs Optic Supermajor小组赛D组胜者组决赛 BO3 第一场 6.3
2018/06/04 DOTA
Python3基础之list列表实例解析
2014/08/13 Python
Python socket实现的简单通信功能示例
2018/08/21 Python
安装docker-compose的两种最简方法
2019/07/30 Python
Tommy Hilfiger美国官网:美国高端休闲领导品牌
2019/01/14 全球购物
国外的一些J2EE面试题一
2012/10/13 面试题
职专应届生求职信
2013/11/16 职场文书
小松树教学反思
2014/02/11 职场文书
教师工作决心书
2015/02/04 职场文书
教师节随笔
2015/08/15 职场文书
高中英语教学反思范文
2016/03/02 职场文书
人民调解协议书
2016/03/21 职场文书
Mysql 如何批量插入数据
2021/04/06 MySQL
vue-cli3.x配置全局的scss的时候报错问题及解决
2022/04/30 Vue.js