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获取GridView选择的行内容
Apr 14 Javascript
JS跨域总结
Aug 30 Javascript
js实现网页倒计时、网站已运行时间功能的代码3例
Apr 14 Javascript
javascript学习笔记(五)原型和原型链详解
Oct 08 Javascript
javascript实现密码验证
Nov 10 Javascript
JS中用try catch对代码运行的性能影响分析
Dec 26 Javascript
微信小程序 本地存储及登录页面处理实例详解
Jan 11 Javascript
深入解析js轮播插件核心代码的实现过程
Apr 14 Javascript
Angularjs按需查询实例代码
Oct 30 Javascript
vue的keep-alive中使用EventBus的方法
Apr 23 Javascript
vue element 中的table动态渲染实现(动态表头)
Nov 21 Javascript
JavaScript this关键字的深入详解
Jan 14 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中url传递中文字符,特殊危险字符的解决方法
2013/08/17 PHP
php获取301跳转URL简单实例
2013/12/16 PHP
php实现与python进行socket通信的方法示例
2017/08/30 PHP
微信企业转账之入口类分装php代码
2018/10/01 PHP
如何让动态插入的javascript脚本代码跑起来。
2007/01/09 Javascript
Some tips of wmi scripting in jscript (1)
2007/04/03 Javascript
JavaScript中判断函数是new还是()调用的区别说明
2011/04/07 Javascript
基于jquery的loading 加载提示效果实现代码
2011/09/01 Javascript
父页面显示遮罩层弹出半透明状态的dialog
2014/03/04 Javascript
a标签的href与onclick事件的区别详解
2014/11/12 Javascript
z-blog SyntaxHighlighter 长代码无法换行解决办法(jquery)
2014/11/16 Javascript
javascript实现下雪效果【实例代码】
2016/05/03 Javascript
JS结合bootstrap实现基本的增删改查功能
2016/07/22 Javascript
AngularJS表单基本操作
2017/01/09 Javascript
最常见和最有用的字符串相关的方法详解
2017/02/06 Javascript
用 js 的 selection range 操作选择区域内容和图片
2017/04/18 Javascript
详解Angular的8个主要构造块
2017/06/20 Javascript
tangram.js库实现js类的方式实例分析
2018/01/06 Javascript
jQuery模拟html下拉多选框的原生实现方法示例
2019/05/30 jQuery
vue组件命名和props命名代码详解
2019/09/01 Javascript
uni app仿微信顶部导航条功能
2019/09/17 Javascript
js实现圆形显示鼠标单击位置
2020/02/11 Javascript
vue 实现element-ui中的加载中状态
2020/11/11 Javascript
[54:09]RNG vs Liquid 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.23
2019/09/05 DOTA
利用Python的Flask框架来构建一个简单的数字商品支付解决方案
2015/03/31 Python
Python中常用操作字符串的函数与方法总结
2016/02/04 Python
Python3远程监控程序的实现方法
2019/07/15 Python
django日志默认打印request请求信息的方法示例
2020/05/17 Python
解决Keras 自定义层时遇到版本的问题
2020/06/16 Python
jupyter notebook远程访问不了的问题解决方法
2021/01/11 Python
pycharm进入时每次都是insert模式的解决方式
2021/02/05 Python
css3中less实现文字长阴影(long shadow)
2020/04/24 HTML / CSS
写一个方法,输入一个文件名和一个字符串,统计这个字符串在这个文件中出现的次数
2016/04/13 面试题
教师见习报告范文
2014/11/03 职场文书
2015元旦标语横幅
2014/12/09 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL