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打开新窗口方法整理
Feb 17 Javascript
JavaSript中变量的作用域闭包的深入理解
May 12 Javascript
jQuery获取上传文件的名称的正则表达式
May 21 Javascript
JavaScript的类型、值和变量小结
Jul 09 Javascript
jQuery+PHP实现可编辑表格字段内容并实时保存
Oct 09 Javascript
分享JavaScript监听全部Ajax请求事件的方法
Aug 28 Javascript
详解AngularJS中$filter过滤器使用(自定义过滤器)
Feb 04 Javascript
详解Vue 事件驱动和依赖追踪
Apr 22 Javascript
基于JavaScript实现幸运抽奖页面
Jul 05 Javascript
vue给对象动态添加属性和值的实例
Sep 09 Javascript
mpvue实现小程序签到金币掉落动画(api实现)
Oct 17 Javascript
React列表栏及购物车组件使用详解
Jun 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 discuz 主题表和回帖表的设计
2009/03/13 PHP
php抽奖小程序的实现代码
2013/06/18 PHP
php使用imagick模块实现图片缩放、裁剪、压缩示例
2014/04/17 PHP
ThinkPHP框架实现session跨域问题的解决方法
2014/07/01 PHP
php实现多城市切换特效
2015/08/09 PHP
YII使用url组件美化管理的方法
2015/12/28 PHP
深入解析PHP的Yii框架中的event事件机制
2016/03/17 PHP
分享精心挑选的23款美轮美奂的jQuery 图片特效插件
2012/08/14 Javascript
JS简单实现登陆验证附效果图
2013/11/19 Javascript
JQUERY 设置SELECT选中项代码
2014/02/07 Javascript
对new functionName()定义一个函数的理解
2014/05/22 Javascript
javascript实现汉字转拼音代码分享
2015/04/20 Javascript
微信WeixinJSBridge API使用实例
2015/05/25 Javascript
基于jQuery日历插件制作日历
2016/03/11 Javascript
JS实现队列与堆栈的方法
2016/04/21 Javascript
AngularJS 整理一些优化的小技巧
2016/08/18 Javascript
将form表单通过ajax实现无刷新提交的简单实例
2016/10/12 Javascript
vue环形进度条组件实例应用
2018/10/10 Javascript
JS/HTML5游戏常用算法之路径搜索算法 随机迷宫算法详解【普里姆算法】
2018/12/13 Javascript
Vue基础学习之项目整合及优化
2019/06/02 Javascript
详解 javascript对象创建模式
2020/10/30 Javascript
Python字符串拼接的几种方法整理
2017/08/02 Python
python实现隐马尔科夫模型HMM
2018/03/25 Python
python ftp 按目录结构上传下载的实现代码
2018/09/12 Python
Python PyInstaller安装和使用教程详解
2020/01/08 Python
python3检查字典传入函数键是否齐全的实例
2020/06/05 Python
销售员自我评价怎么写
2013/09/19 职场文书
春节晚会主持词
2014/03/24 职场文书
大学生活自我评价
2014/04/09 职场文书
爱祖国演讲稿
2014/05/04 职场文书
党支部创先争优承诺书
2014/08/30 职场文书
工作疏忽、懈怠的检讨书
2014/09/11 职场文书
团代会开幕词
2015/01/28 职场文书
2016廉政教育学习心得体会
2016/01/25 职场文书
python opencv将多个图放在一个窗口的实例详解
2022/02/28 Python
Arthas排查Kubernetes中应用频繁挂掉重启异常
2022/02/28 MySQL