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 相关文章推荐
js打印纸函数代码(递归)
Jun 18 Javascript
妙用Jquery的val()方法
Jun 27 Javascript
ECMAScript6函数剩余参数(Rest Parameters)
Jun 12 Javascript
javascript中数组和字符串的方法对比
Jul 20 Javascript
教你JS中的运算符乘方、开方及变量格式转换
Aug 09 Javascript
javascript输出AscII码扩展集中的字符方法
Dec 26 Javascript
webpack项目调试以及独立打包配置文件的方法
Feb 28 Javascript
vue中$set的使用(结合在实际应用中遇到的坑)
Jul 10 Javascript
详解JSON Web Token 入门教程
Jul 30 Javascript
Javascript中弹窗confirm与prompt的区别
Oct 26 Javascript
如何制作一个Node命令行图像识别工具
Dec 12 Javascript
微信小程序实现列表滚动头部吸顶的示例代码
Jul 12 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
使用网络地址转换实现多服务器负载均衡
2006/10/09 PHP
在PHP中PDO解决中文乱码问题的一些补充
2010/09/06 PHP
PHP实现QQ、微信和支付宝三合一收款码实例代码
2018/02/19 PHP
显示js对象所有属性和方法的函数
2009/10/16 Javascript
firefox插件Firebug的使用教程
2010/01/02 Javascript
JavaScript移除数组元素减少长度的方法
2013/09/05 Javascript
使用原生JS实现弹出层特效
2014/12/22 Javascript
JavaScript函数作用域链分析
2015/02/13 Javascript
js实现的四级左侧网站分类菜单实例
2015/05/06 Javascript
javascript函数特点实例分析
2015/05/14 Javascript
apply和call方法定义及apply和call方法的区别
2015/11/15 Javascript
jquery实现表格隔行换色效果
2015/11/19 Javascript
JavaScript制作颜色反转小游戏
2016/09/25 Javascript
Chrome浏览器的alert弹窗禁止再次弹出后恢复的方法
2016/12/30 Javascript
javascript 初学教程及五子棋小程序的简单实现
2017/07/04 Javascript
Angular 1.x个人使用的经验小结
2017/07/19 Javascript
微信小程序媒体组件详解(视频,音乐,图片)
2017/09/19 Javascript
200行HTML+JavaScript实现年会抽奖程序
2019/01/22 Javascript
vue如何使用async、await实现同步请求
2019/12/09 Javascript
javascript Canvas动态粒子连线
2020/01/01 Javascript
JavaScript实现10秒后再次获取验证码
2020/12/02 Javascript
Vue实现简易购物车页面
2020/12/30 Vue.js
用Python创建声明性迷你语言的教程
2015/04/13 Python
各个系统下的Python解释器相关安装方法
2015/10/12 Python
Python如何import文件夹下的文件(实现方法)
2017/01/24 Python
python递归函数绘制分形树的方法
2018/06/22 Python
python利用os模块编写文件复制功能——copy()函数用法
2020/07/13 Python
html5-websocket基于远程方法调用的数据交互实现
2012/12/04 HTML / CSS
如何提高JDBC的性能
2013/04/30 面试题
12岁生日感言
2014/01/21 职场文书
劲霸男装广告词
2014/03/21 职场文书
幼儿园小班评语
2014/04/18 职场文书
卫生系统先进事迹
2014/05/13 职场文书
2015年食堂工作总结报告
2015/04/23 职场文书
SQL SERVER中常用日期函数的具体使用
2021/04/08 SQL Server
SQLServer中JSON文档型数据的查询问题解决
2021/06/27 SQL Server