JavaScript比较两个数组的内容是否相同(推荐)


Posted in Javascript onMay 02, 2017

今天意外地发现JavaScript是不能用==或===操作符直接比较两个数组是否相等的。

alert([]==[]);  // false
alert([]===[]);  // false

以上两句代码都会弹出false。

因为JavaScript里面Array是对象,==或===操作符只能比较两个对象是否是同一个实例,也就是是否是同一个对象引用。目前JavaScript没有内置的操作符判断对象的内容是否相同。

但是惯性思维让人以为数组也是值,是可以比较的。

如果要比较数组是否相等,就只能遍历数组元素比较。

在网上流传很普遍的一种做法是将数组转换成字符串:

JSON.stringify(a1) == JSON.stringify(a2)

 或

a1.toString() == a2.toString()

请不要使用这种方法。

这种方法在某些情况下是可行的,当两个数组的元素顺序相同且元素都可以转换成字符串的情况下确实可行,但是这样的代码存有隐患,比如数字被转换成字符串,数字“1”和字符串“1”会被认为相等,可能造成调试困难,不推荐使用。

在StackOverflow上有大神已经提供了正确的方法,我就做下搬运工吧:

// 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});

大神还顺手给了比较Object的方法:

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;
}

以上所述是小编给大家介绍的JavaScript比较两个数组的内容是否相同(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
jQuery入门第一课 jQuery选择符
Mar 14 Javascript
jQuery的.live()和.die() 使用介绍
Sep 10 Javascript
js 调用百度地图api并在地图上进行打点添加标注
May 13 Javascript
javascript在网页中实现读取剪贴板粘贴截图功能
Jun 07 Javascript
JS数组去掉重复数据只保留一条的实现代码
Aug 11 Javascript
Bootstrap table两种分页示例
Dec 23 Javascript
Angular 2父子组件数据传递之@Input和@Output详解 (上)
Jul 05 Javascript
vue-cli脚手架config目录下index.js配置文件的方法
Mar 13 Javascript
浅析Vue实例以及生命周期
Aug 14 Javascript
详解JavaScript的内存空间、赋值和深浅拷贝
Apr 17 Javascript
JavaScript之数组扁平化详解
Jun 03 Javascript
Vue项目配置跨域访问和代理proxy设置方式
Sep 08 Javascript
xmlplus组件设计系列之分隔框(DividedBox)(8)
May 02 #Javascript
xmlplus组件设计系列之树(Tree)(9)
May 02 #Javascript
详解Vue2.X的路由管理记录之 钩子函数(切割流水线)
May 02 #Javascript
令按钮悬浮在(手机)页面底部的实现方法
May 02 #Javascript
Vue2.0表单校验组件vee-validate的使用详解
May 02 #Javascript
ES6学习教程之对象的扩展详解
May 02 #Javascript
Javascript ES6中数据类型Symbol的使用详解
May 02 #Javascript
You might like
德生PL990的分析评价
2021/03/02 无线电
PHP 9 大缓存技术总结
2015/09/17 PHP
Docker配置PHP开发环境教程
2016/12/21 PHP
使用onbeforeunload属性后的副作用
2007/03/08 Javascript
离开页面时检测表单元素是否被修改,提示保存的js代码
2010/08/25 Javascript
jQuery.prototype.init选择器构造函数源码思路分析
2013/02/05 Javascript
setInterval,setTimeout与jquery混用的问题
2013/04/08 Javascript
node.js中的path.normalize方法使用说明
2014/12/08 Javascript
Angular设置title信息解决SEO方面存在问题
2016/08/19 Javascript
详解微信小程序 wx.uploadFile 的编码坑
2017/01/23 Javascript
easyui下拉框动态级联加载的示例代码
2017/11/29 Javascript
AngularJS实现与后台服务器进行交互的示例讲解
2018/08/13 Javascript
微信小程序内拖动图片实现移动、放大、旋转的方法
2018/09/04 Javascript
js实现盒子移动动画效果
2020/08/09 Javascript
ant design中upload组件上传大文件,显示进度条进度的实例
2020/10/29 Javascript
vue 使用localstorage实现面包屑的操作
2020/11/16 Javascript
小程序实现密码输入框
2020/11/16 Javascript
js实现简单图片拖拽效果
2021/02/22 Javascript
Python中条件选择和循环语句使用方法介绍
2013/03/13 Python
Python中Continue语句的用法的举例详解
2015/05/14 Python
让Django支持Sql Server作后端数据库的方法
2018/05/29 Python
pandas求两个表格不相交的集合方法
2018/12/08 Python
python实现K近邻回归,采用等权重和不等权重的方法
2019/01/23 Python
使用python制作游戏下载进度条的代码(程序说明见注释)
2019/10/24 Python
浅谈Python中re.match()和re.search()的使用及区别
2020/04/14 Python
Python数据正态性检验实现过程
2020/04/18 Python
基于PyQT实现区分左键双击和单击
2020/05/19 Python
Bergfreunde丹麦:登山装备网上零售商
2017/02/26 全球购物
具有防紫外线功能的高性能钓鱼服装:Hook&Tackle
2018/08/16 全球购物
No7 Beauty美国官网:英国国民护肤品牌
2019/10/31 全球购物
四年大学生活的个人自我评价
2013/12/11 职场文书
综合实践活动总结
2014/05/05 职场文书
后勤管理员岗位职责
2014/08/27 职场文书
幼儿园小班个人总结
2015/02/12 职场文书
学校勤俭节约倡议书
2015/04/29 职场文书
python turtle绘图
2022/05/04 Python