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.ui.dialog 增加“在当前鼠标位置打开”的功能
Nov 24 Javascript
Javascript 键盘keyCode键码值表
Dec 24 Javascript
设为首页和收藏的Javascript代码(亲测兼容IE,Firefox,chrome等浏览器)
Nov 18 Javascript
用jquery写的菜单从左往右滑动出现
Apr 11 Javascript
Javascript学习笔记之 函数篇(二) : this 的工作机制
Jun 24 Javascript
深入理解Javascript中this的作用域
Aug 12 Javascript
原生js实现日期联动
Jan 12 Javascript
值得分享的Bootstrap Table使用教程
Nov 23 Javascript
详谈$.data()的用法和作用
Feb 13 Javascript
使用node.js对音视频文件加密的实例代码
Aug 30 Javascript
详解vue-cli构建项目反向代理配置
Sep 07 Javascript
js实现超级玛丽小游戏
Mar 18 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 执行系统外部命令 system() exec() passthru()
2009/08/11 PHP
php curl常见错误:SSL错误、bool(false)
2011/12/28 PHP
php计算数组相同值出现次数的代码(array_count_values)
2015/01/20 PHP
利用PHPExcel读取Excel的数据和导出数据到Excel
2017/05/12 PHP
Alliance vs Liquid BO3 第三场2.13
2021/03/10 DOTA
国外的为初学者写的JavaScript教程
2008/06/09 Javascript
一个简单的js渐显(fadeIn)渐隐(fadeOut)类
2010/06/19 Javascript
异步加载script的代码
2011/01/12 Javascript
改变文件域的样式实现思路同时兼容ie、firefox
2013/10/23 Javascript
JQuery异步加载无限下拉框级联功能实现示例
2014/02/19 Javascript
理解javascript中Map代替循环
2016/02/26 Javascript
jqGrid用法汇总(全经典)
2016/06/28 Javascript
解决Vue打包之后文件路径出错的问题
2018/03/06 Javascript
js+css实现红包雨效果
2018/07/12 Javascript
Vue实战教程之仿肯德基宅急送App
2019/07/19 Javascript
微信小程序实现传递多个参数与事件处理
2019/08/12 Javascript
webpack打包html里面img后src为“[object Module]”问题
2019/12/22 Javascript
JS实现星星海特效
2019/12/24 Javascript
[00:56]PWL开团时刻DAY8——追追追追追!
2020/11/09 DOTA
python 判断自定义对象类型
2009/03/21 Python
Python模仿POST提交HTTP数据及使用Cookie值的方法
2014/11/10 Python
浅析python递归函数和河内塔问题
2017/04/18 Python
Python利用字典将两个通讯录文本合并为一个文本实例
2018/01/16 Python
通过Pandas读取大文件的实例
2018/06/07 Python
Python 实现中值滤波、均值滤波的方法
2019/01/09 Python
python opencv minAreaRect 生成最小外接矩形的方法
2019/07/01 Python
Python with标签使用方法解析
2020/01/17 Python
构建高效的python requests长连接池详解
2020/05/02 Python
自动化专业个人求职信范文
2013/12/30 职场文书
《地震中的父与子》教学反思
2014/04/10 职场文书
大学国际贸易专业自荐信
2014/06/05 职场文书
行政部经理助理岗位职责
2014/06/15 职场文书
电影雨中的树观后感
2015/06/15 职场文书
入党积极分子培养联系人意见
2015/08/12 职场文书
解决Vmware虚拟机安装centos8报错“Section %Packages Does Not End With %End. Pane Is Dead”
2022/06/01 Servers
ubuntu20.04虚拟机无法上网的问题及解决
2022/12/24 Servers