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 相关文章推荐
HTA版JSMin(省略修饰语若干)基于javascript语言编写
Dec 24 Javascript
js将long日期格式转换为标准日期格式实现思路
Apr 07 Javascript
JS中表单的使用小结
Jan 11 Javascript
javascript实例分享---具有立体效果的图片特效
Jun 08 Javascript
通过JS动态创建一个html DOM元素并显示
Oct 15 Javascript
JS模拟并美化的表单控件完整实例
Aug 19 Javascript
javascript实现数组去重的多种方法
Mar 14 Javascript
AngularJS之页面跳转Route实例代码
Mar 10 Javascript
Node.js 中exports 和 module.exports 的区别
Mar 14 Javascript
从零开始学习Node.js系列教程之设置HTTP头的方法示例
Apr 13 Javascript
Vue-component全局注册实例
Sep 06 Javascript
vue路由结构可设一层方便动态添加路由操作
Aug 31 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运行速度的一些小技巧分享
2012/07/03 PHP
Yii2使用swiftmailer发送邮件的方法
2016/05/03 PHP
Fleaphp常见函数功能与用法示例
2016/11/15 PHP
PHP实现的登录页面信息提示功能示例
2017/07/24 PHP
js 中 document.createEvent的用法
2010/08/29 Javascript
ExtJS下 Ext.Direct加载和提交过程排错小结
2013/04/02 Javascript
jQuery extend 的简单实例
2013/09/18 Javascript
jQuery 取值、赋值的基本方法整理
2014/03/31 Javascript
深入理解js函数的作用域与this指向
2016/05/28 Javascript
vue组件间通信解析
2017/03/01 Javascript
详解angularjs popup-table 弹出框表格指令
2017/09/20 Javascript
vue 之 .sync 修饰符示例详解
2018/04/21 Javascript
vue使用Google地图的实现示例代码
2018/12/19 Javascript
详解js实时获取并显示当前时间的方法
2019/05/10 Javascript
详解vue 2.6 中 slot 的新用法
2019/07/09 Javascript
vue前后分离调起微信支付
2019/07/29 Javascript
微信小程序 简易计算器实现代码实例
2019/09/02 Javascript
layui时间控件选择时间范围的实现方法
2019/09/28 Javascript
[47:03]Ti4第二日主赛事败者组 LGD vs iG 2
2014/07/21 DOTA
python 合并文件的具体实例
2013/08/08 Python
《Python之禅》中对于Python编程过程中的一些建议
2015/04/03 Python
在windows系统中实现python3安装lxml
2016/03/23 Python
python flask 多对多表查询功能
2017/06/25 Python
python 获取list特定元素下标的实例讲解
2018/04/09 Python
Flask缓存静态文件的具体方法
2020/08/02 Python
css3制作动态进度条以及附加jQuery百分比数字显示
2012/12/13 HTML / CSS
css3 给页面加个半圆形导航条主要利用旋转和倾斜样式
2014/02/10 HTML / CSS
摩顿布朗英国官方网上商店:奢华沐浴、身体和头发护理
2016/10/29 全球购物
QQ空间主人寄语大全
2014/04/12 职场文书
2014年教师节红领巾广播稿
2014/09/10 职场文书
二审答辩状范文
2015/05/22 职场文书
庆七一活动简报
2015/07/20 职场文书
煤矿安全生产工作总结
2015/08/13 职场文书
Mysql官方性能测试工具mysqlslap的使用简介
2021/05/21 MySQL
68行Python代码实现带难度升级的贪吃蛇
2022/01/18 Python
4种方法python批量修改替换列表中元素
2022/04/07 Python