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 相关文章推荐
新页面打开实际尺寸的图片
Aug 25 Javascript
JavaScript使用prototype定义对象类型
Feb 07 Javascript
javascript 贪吃蛇实现代码
Nov 22 Javascript
jQuery+CSS3实现3D立方体旋转效果
Nov 10 Javascript
JavaScript的设计模式经典之建造者模式
Feb 24 Javascript
javascript拖拽效果延伸学习
Apr 04 Javascript
AngularJS 指令详细介绍
Jul 27 Javascript
获取select的value、text值的简单示例(jquery与javascript)
Dec 07 Javascript
js求数组中全部数字可拼接出的最大整数示例代码
Aug 25 Javascript
js new Date()实例测试
Oct 31 Javascript
Jquery属性的获取/设置及样式添加/删除操作技巧分析
Dec 23 jQuery
详解uniapp的全局变量实现方式
Jan 11 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实现的博客欢迎提示功能(很特别哦)
2014/06/05 PHP
PHP实现多级分类生成树的方法示例
2017/02/07 PHP
laravel利用中间件防止未登录用户直接访问后台的方法
2019/09/30 PHP
JavaScript的eval JSON object问题
2009/11/15 Javascript
js实现兼容IE6与IE7的DIV高度
2010/05/13 Javascript
JavaScript中的View-Model使用介绍
2011/08/11 Javascript
jquery实现的鼠标下拉滚动置顶效果
2014/07/24 Javascript
javascript实现的闭包简单实例
2015/07/17 Javascript
浅谈JavaScript中的this指针和引用知识
2016/08/05 Javascript
jQuery的 $.ajax防止重复提交的两种方法(推荐)
2016/10/14 Javascript
从零学习node.js之文件操作(三)
2017/02/21 Javascript
Vue组件化开发思考
2018/02/02 Javascript
Linux Centos7.2下安装nodejs&amp;npm配置全局路径的教程
2018/05/15 NodeJs
Vue中的作用域CSS和CSS模块的区别
2018/10/09 Javascript
Nuxt v-bind绑定img src不显示的解决
2019/12/05 Javascript
ES6的异步操作之promise用法和async函数的具体使用
2019/12/06 Javascript
JS实现简单贪吃蛇小游戏
2020/10/28 Javascript
[02:45]2016年中国刀塔全程回顾,完美“圣”典即将上演
2016/12/15 DOTA
[01:01:41]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Magma BO3 第二场 1月31日
2021/03/11 DOTA
python访问sqlserver示例
2014/02/10 Python
python版opencv摄像头人脸实时检测方法
2018/08/03 Python
基于python实现蓝牙通信代码实例
2019/11/19 Python
Python计算IV值的示例讲解
2020/02/28 Python
基于python连接oracle导并出数据文件
2020/04/28 Python
css3学习心得分享
2013/08/19 HTML / CSS
10分钟理解CSS3 FlexBox弹性布局
2018/12/20 HTML / CSS
Haglöfs瑞典官方网站:haglofs火柴棍,欧洲顶级户外品牌
2018/10/18 全球购物
幼师岗位求职简历的自荐信格式
2013/09/21 职场文书
学生社团文化节开幕式主持词
2014/03/28 职场文书
科技之星事迹材料
2014/06/02 职场文书
租房协议书样本
2014/08/20 职场文书
云台山导游词
2015/02/03 职场文书
2015年语文教研组工作总结
2015/05/23 职场文书
复活读书笔记
2015/06/29 职场文书
详解TypeScript中的类型保护
2021/04/29 Javascript
一劳永逸彻底解决pip install慢的办法
2021/05/24 Python