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的ajax功能实现web service的json转化
Aug 29 Javascript
Array 重排序方法和操作方法的简单实例
Jan 24 Javascript
Js 正则表达式知识汇总
Dec 02 Javascript
Javascript的闭包详解
Dec 26 Javascript
js实现touch移动触屏滑动事件
Apr 17 Javascript
js实现用户离开页面前提示是否离开此页面的方法(包括浏览器按钮事件)
Jul 18 Javascript
浏览器环境下JavaScript脚本加载与执行探析之动态脚本与Ajax脚本注入
Jan 19 Javascript
用jquery获取自定义的标签属性的值简单实例
Sep 17 Javascript
JavaScript中 DOM操作方法小结
Apr 25 Javascript
JS鼠标3次点击事件实现代码及扩展思路
Sep 12 Javascript
基于Vue的ajax公共方法(详解)
Jan 20 Javascript
逐行分析鸿蒙系统的 JavaScript 框架(推荐)
Sep 17 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自定义函数返回多个值
2006/11/26 PHP
php curl选项列表(超详细)
2013/07/01 PHP
ThinkPHP入口文件设置及相关注意事项分析
2014/12/05 PHP
PHP封装curl的调用接口及常用函数详解
2018/05/31 PHP
php面向对象基础详解【星际争霸游戏案例】
2020/01/23 PHP
js 编写规范
2010/03/03 Javascript
JavaScript 对象的属性和方法4种不同的类型
2010/03/19 Javascript
js实现addClass,removeClass,hasClass的函数代码
2011/07/13 Javascript
基于javascript实现图片懒加载
2016/01/05 Javascript
JavaScript数据操作_浅谈原始值和引用值的操作本质
2016/08/23 Javascript
JS取模、取商及取整运算方法示例
2016/10/13 Javascript
jQuery自定义插件详解及实例代码
2016/12/29 Javascript
详解JS构造函数中this和return
2017/09/16 Javascript
解读vue生成的文件目录结构及说明
2017/11/27 Javascript
vue获取当前点击的元素并传值的实例
2018/03/09 Javascript
在vue项目中使用sass的配置方法
2018/03/20 Javascript
Vue插件之滑动验证码
2019/09/21 Javascript
vue路由守卫,限制前端页面访问权限的例子
2019/11/11 Javascript
JavaScript使用setTimeout实现倒计时效果
2021/02/19 Javascript
python将图片文件转换成base64编码的方法
2015/03/14 Python
老生常谈Python序列化和反序列化
2017/06/28 Python
python中的协程深入理解
2019/06/10 Python
在macOS上搭建python环境的实现方法
2019/08/13 Python
python 在threading中如何处理主进程和子线程的关系
2020/04/25 Python
如何查看python关键字
2021/01/17 Python
加大码胸罩、内裤和服装:Just My Size
2019/03/21 全球购物
品牌服务方案
2014/06/03 职场文书
韩语专业职业生涯规划范文:成功之路就在我们脚下
2014/09/11 职场文书
小学教师自我评价
2015/03/04 职场文书
物流仓管员岗位职责
2015/04/01 职场文书
二审答辩状范文
2015/05/22 职场文书
全陪导游词开场白
2015/05/29 职场文书
新教师教学工作总结
2015/08/12 职场文书
教育教学工作反思
2016/02/24 职场文书
浅谈golang 中time.After释放的问题
2021/05/05 Golang
Linux在两个服务器直接传文件的操作方法
2022/08/05 Servers