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 面向对象编程(coolshell)
Mar 18 Javascript
cookie的复制与使用记住用户名实现代码
Nov 04 Javascript
利用JS解决ie6不支持max-width,max-height问题的方法
Jan 02 Javascript
JavaScript对象的property属性详解
Apr 01 Javascript
js返回前一页刷新本页重载页面
Jul 29 Javascript
javascript实现日期按月份加减
May 15 Javascript
JavaScript编程中window的location与history对象详解
Oct 26 Javascript
jQuery mobile类库使用时加载导航历史的方法简介
Dec 04 Javascript
jQuery 中的 DOM 操作
Apr 26 Javascript
使用jquery获取url及url参数的简单实例
Jun 14 Javascript
js 获取当前web应用的上下文路径实现方法
Aug 19 Javascript
jQuery之动画效果大全
Nov 09 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
如何在WIN2K下安装PHP4.04
2006/10/09 PHP
php输出表格的实现代码(修正版)
2010/12/29 PHP
php使用curl抓取qq空间的访客信息示例
2014/02/28 PHP
理解javascript回调函数
2014/12/28 Javascript
JavaScript给每一个li节点绑定点击事件的实现方法
2016/12/01 Javascript
利用require.js与angular搭建spa应用的方法实例
2017/07/19 Javascript
基于Axios 常用的请求方法别名(详解)
2018/03/13 Javascript
jQuery中图片展示插件highslide.js的简单dom
2018/04/22 jQuery
Vue使用watch监听一个对象中的属性的实现方法
2019/05/10 Javascript
微信小程序系列之自定义顶部导航功能
2019/05/21 Javascript
layer弹出层取消遮罩的方法
2019/09/25 Javascript
JavaScript交换两个变量方法实例
2019/11/25 Javascript
angular组件间传值测试的方法详解
2020/05/07 Javascript
VUE前端从后台请求过来的数据进行转换数据结构操作
2020/11/11 Javascript
Vue中避免滥用this去读取data中数据
2021/03/02 Vue.js
Python-基础-入门 简介
2014/08/09 Python
JS设计模式之责任链模式实例详解
2018/02/03 Python
opencv设置采集视频分辨率方式
2019/12/10 Python
python3中pip3安装出错,找不到SSL的解决方式
2019/12/12 Python
Django调用百度AI接口实现人脸注册登录代码实例
2020/04/23 Python
html5版canvas自由拼图实例
2014/10/15 HTML / CSS
Nisbets爱尔兰:英国最大的厨房和餐饮设备供应商
2019/01/26 全球购物
台湾屈臣氏网路商店:Watsons台湾
2020/12/29 全球购物
个人简历的自荐信
2013/10/23 职场文书
资产经营总监岗位职责
2013/12/04 职场文书
求职简历中个人的自我评价
2013/12/25 职场文书
八一演出活动方案
2014/02/03 职场文书
颁奖晚会主持词
2014/03/25 职场文书
小班下学期评语
2014/05/04 职场文书
圣诞节活动策划方案
2014/06/09 职场文书
教师师德师风自我剖析材料
2014/09/29 职场文书
企业党的群众路线教育实践活动学习心得体会
2014/10/31 职场文书
vue+element ui实现锚点定位
2021/06/29 Vue.js
详解Vue slot插槽
2021/11/20 Vue.js
Python Django项目和应用的创建详解
2021/11/27 Python
实例详解Python的进程,线程和协程
2022/03/13 Python