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 相关文章推荐
JavaScript 的方法重载效果
Aug 07 Javascript
用jquery设置按钮的disabled属性的实现代码
Nov 28 Javascript
JS获取键盘上任意按键的值(实例代码)
Nov 12 Javascript
js用拖动滑块来控制图片大小的方法
Feb 27 Javascript
AngularJS快速入门
Apr 02 Javascript
JS实现图文并茂的tab选项卡效果示例【附demo源码下载】
Sep 21 Javascript
Linux系统中利用node.js提取Word(doc/docx)及PDF文本的内容
Jun 17 Javascript
JS实现简单的选择题测评系统代码思路详解(demo)
Sep 03 Javascript
详解自定义ajax支持跨域组件封装
Feb 08 Javascript
React学习之JSX与react事件实例分析
Jan 06 Javascript
vue随机验证码组件的封装实现
Feb 19 Javascript
js实现查询商品案例
Jul 22 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
转生史莱姆:萌王第一次撸串开心到飞起,哥布塔撸串却神似界王神
2018/11/30 日漫
php代码运行时间查看类代码分享
2011/08/06 PHP
PHP实现的曲线统计图表示例
2016/11/10 PHP
PHP从零开始打造自己的MVC框架之路由类实现方法分析
2019/06/03 PHP
Javascript常用运算符(Operators)-javascript基础教程
2007/12/14 Javascript
JavaScript Event学习第五章 高级事件注册模型
2010/02/07 Javascript
innerHTML 和 getElementsByName 在IE下面的bug 的解决
2010/04/09 Javascript
JS按位非(~)运算符与~~运算符的理解分析
2011/07/31 Javascript
有关于JS辅助函数inherit()的问题
2013/04/07 Javascript
在JavaScript里防止事件函数高频触发和高频调用的方法
2014/09/06 Javascript
NodeJS Web应用监听sock文件实例
2015/02/18 NodeJs
js实现文字跟随鼠标移动而移动的方法
2015/02/28 Javascript
JavaScript Split()方法
2015/12/18 Javascript
JavaScript用构造函数如何获取变量的类型名
2016/12/23 Javascript
详解vue 模版组件的三种用法
2017/07/21 Javascript
Vue.js 实现数据展示全部和收起功能
2018/09/05 Javascript
CKeditor4 字体颜色功能配置方法教程
2019/06/26 Javascript
vue 实现图片懒加载功能
2020/12/31 Vue.js
[01:00:25]NB vs Secret 2018国际邀请赛小组赛BO1 B组加赛 8.19
2018/08/21 DOTA
[01:14]DOTA2 7.22版本新增神杖效果展示(智力英雄篇)
2019/05/29 DOTA
pygame学习笔记(6):完成一个简单的游戏
2015/04/15 Python
打包PyQt5应用时的注意事项
2020/02/14 Python
python模拟斗地主发牌
2020/04/22 Python
Django admin管理工具TabularInline类用法详解
2020/05/14 Python
Python利用Xpath选择器爬取京东网商品信息
2020/06/01 Python
Python爬虫制作翻译程序的示例代码
2021/02/22 Python
英国在线购买轮胎、预订汽车、汽车维修和装配网站:Protyre
2020/04/12 全球购物
下面代码从性能上考虑,有什么问题
2015/04/03 面试题
葡萄牙语专业个人求职信
2013/12/10 职场文书
2014年党员公开承诺践诺书
2014/03/25 职场文书
董事长助理岗位职责
2015/02/11 职场文书
幼儿园个人总结
2015/02/28 职场文书
会计专业求职信范文
2015/03/19 职场文书
归途列车观后感
2015/06/17 职场文书
2016年综治宣传月活动宣传标语口号
2016/03/16 职场文书
委托开发合同书(标准版)
2019/08/07 职场文书