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 判断浏览器类型及版本
Feb 21 Javascript
jQuery链式操作如何实现以及为什么要用链式操作
Jan 17 Javascript
jquery 倒计时效果实现秒杀思路
Sep 11 Javascript
form表单action提交的js部分与html部分
Jan 07 Javascript
js实现类似于add(1)(2)(3)调用方式的方法
Mar 04 Javascript
JQuery中属性过滤选择器用法实例分析
May 18 Javascript
详解javascript函数的参数
Nov 10 Javascript
JavaScript 不支持 indexof 该如何解决
Mar 30 Javascript
JavaScript中的prototype原型学习指南
May 09 Javascript
详解Node.js模块间共享数据库连接的方法
May 24 Javascript
js实现多张图片延迟加载效果
Jul 17 Javascript
Vue仿支付宝支付功能
May 25 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
php构造函数实例讲解
2013/11/13 PHP
php关联数组快速排序的方法
2015/04/17 PHP
php版微信小店API二次开发及使用示例
2016/11/12 PHP
Laravel 批量更新多条数据的示例
2017/11/27 PHP
javascript之大字符串的连接的StringBuffer 类
2007/05/08 Javascript
用Javascript评估用户输入密码的强度(Knockout版)
2011/11/30 Javascript
JQuery之focus函数使用介绍
2013/08/20 Javascript
一个html5播放视频的video控件只支持android的默认格式mp4和3gp
2014/05/08 Javascript
js判断滚动条是否已到页面最底部或顶部实例
2014/11/20 Javascript
浅谈Javascript数组索引
2015/07/29 Javascript
实现音乐播放器的代码(html5+css3+jquery)
2015/08/04 Javascript
引用jquery框架后出错的解决方法
2016/08/09 Javascript
老生常谈javascript中逻辑运算符&amp;&amp;和||的返回值问题
2017/04/13 Javascript
react-native-tab-navigator组件的基本使用示例代码
2017/09/07 Javascript
JS Testing Properties 判断属性是否在对象里的方法
2017/10/01 Javascript
vue中Element-ui 输入银行账号每四位加一个空格的实现代码
2018/09/14 Javascript
inquirer.js一个用户与命令行交互的工具详解
2019/05/18 Javascript
Echarts地图添加引导线效果(labelLine)
2019/09/30 Javascript
jquery实现烟花效果(面向对象)
2020/03/10 jQuery
[45:34]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第一场 12.18
2020/12/19 DOTA
删除目录下相同文件的python代码(逐级优化)
2012/05/25 Python
使用Python进行稳定可靠的文件操作详解
2013/12/31 Python
python3爬取淘宝信息代码分析
2018/02/10 Python
对Python 网络设备巡检脚本的实例讲解
2018/04/22 Python
python 检查文件mime类型的方法
2018/12/08 Python
pytorch torchvision.ImageFolder的用法介绍
2020/02/20 Python
详解tensorflow之过拟合问题实战
2020/11/01 Python
Python包资源下载路径报404解决方案
2020/11/05 Python
Python系统公网私网流量监控实现流程
2020/11/23 Python
幼儿园招生广告
2014/03/19 职场文书
七夕情人节促销方案
2014/06/07 职场文书
治庸问责心得体会
2014/09/12 职场文书
2014年党员自我评议(5篇)
2014/09/12 职场文书
群众路线剖析材料范文
2014/10/09 职场文书
教师个人自我评价
2015/03/04 职场文书
离婚起诉状范本
2015/05/19 职场文书