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 事件小结 表格区别
Aug 13 Javascript
JQuery调用绑定click事件的3种写法
Mar 28 Javascript
javascript用正则表达式过滤空格的实现代码
Jun 14 Javascript
详解angular中通过$location获取路径(参数)的写法
Mar 21 Javascript
JS简单实现数组去重的方法示例
Mar 27 Javascript
ES6 Promise对象概念与用法分析
Apr 01 Javascript
vue.js删除动态绑定的radio的指定项
Jun 02 Javascript
vue使用iframe嵌入网页的示例代码
Jun 09 Javascript
JS实现二维数组元素的排列组合运算简单示例
Jan 28 Javascript
微信小程序实现卡片层叠滑动效果
Jun 21 Javascript
jquery.pager.js实现分页效果
Jul 29 jQuery
vue-router懒加载的3种方式汇总
Feb 28 Vue.js
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
Drupal7中常用的数据库操作实例
2014/03/02 PHP
php版淘宝网查询商品接口代码示例
2014/06/17 PHP
PHP中关于php.ini参数优化详解
2020/02/28 PHP
PhpStorm的使用教程(本地运行PHP+远程开发+快捷键)
2020/03/26 PHP
php7 新增功能实例总结
2020/05/25 PHP
IE和FireFox(FF)中js和css的不同
2009/04/13 Javascript
ie和firefox不兼容的解决方法集合
2009/04/28 Javascript
输入自动提示搜索提示功能的使用说明:sugggestion.txt
2013/09/02 Javascript
深入理解JavaScript系列(40):设计模式之组合模式详解
2015/03/04 Javascript
JavaScript实现自动消除按钮功能的方法
2015/08/05 Javascript
JavaScript中的操作符类型转换示例总结
2016/05/30 Javascript
详解Sea.js中Module.exports和exports的区别
2017/02/12 Javascript
bootstrap table操作技巧分享
2017/02/15 Javascript
JavaScript插入排序算法原理与实现方法示例
2018/08/06 Javascript
使用electron制作满屏心特效的示例代码
2018/11/27 Javascript
详解50行代码,Node爬虫练手项目
2019/04/22 Javascript
js+html实现点名系统功能
2019/11/05 Javascript
Js参数RSA加密传输之jsencrypt.js的使用
2020/02/07 Javascript
Vue.js中使用Vuex实现组件数据共享案例
2020/07/31 Javascript
python 七种邮件内容发送方法实例
2014/04/22 Python
Python yield 小结和实例
2014/04/25 Python
Python生成不重复随机值的方法
2015/05/11 Python
Python装饰器的执行过程实例分析
2018/06/04 Python
python在回调函数中获取返回值的方法
2019/02/22 Python
Python-numpy实现灰度图像的分块和合并方式
2020/01/09 Python
django修改models重建数据库的操作
2020/03/31 Python
解决在keras中使用model.save()函数保存模型失败的问题
2020/05/21 Python
HTML中使用SVG与SVG预定义形状元素介绍
2013/06/28 HTML / CSS
CLR与IL分别是什么含义
2016/08/23 面试题
什么叫应用程序域?什么是托管代码?什么是强类型系统?什么是装箱和拆箱?什么是重载?CTS、CLS和CLR分别作何解释?
2012/05/23 面试题
金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥1011)-> (一千零一拾一元整)输出
2015/05/29 面试题
求职简历推荐信范文
2013/12/02 职场文书
法院授权委托书格式
2014/09/28 职场文书
聘任证明怎么写
2015/03/02 职场文书
2015年后备干部工作总结
2015/05/15 职场文书
JavaScript原型链中函数和对象的理解
2022/06/16 Javascript