Javascript中有'=='和'==='两种相等比较,后者是全等,会判断数据类型,前者是相等,在比较时,会发生隐式转换。

如果将两个对象做'=='比较,结果会如何呢?

比如有如下两个对象:

var obj1 = {name: "Nicole",sex : "female"
}var obj2 = {name: "Nicole",sex : "female"
}//Outputs: false
console.log(obj1 == obj2);//Outputs: false
console.log(obj1 === obj2);

可以看到,哪怕两个对象的属性完全一样,无论是'=='或者'===',返回都是false。

原因:对象通过指针指向的内存地址来做比较。

继续上面的例子:

1 var obj3 = obj1;
2
3 //Outputs: true
4 console.log(obj1 == obj3);
5
6 //Outputs: true
7 console.log(obj1 === obj3);

如果想根据两个对象的属性是否相等,来判断对象是否相等,可以参考underscore:isEqual(obj1, obj2):

// Internal recursive comparison function for `isEqual`.var eq, deepEq;eq = function(a, b, aStack, bStack) {// Identical objects are equal. `0 === -0`, but they aren't identical.// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).if (a === b) return a !== 0 || 1 / a === 1 / b;// `null` or `undefined` only equal to itself (strict comparison).if (a == null || b == null) return false;// `NaN`s are equivalent, but non-reflexive.if (a !== a) return b !== b;// Exhaust primitive checksvar type = typeof a;if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;return deepEq(a, b, aStack, bStack);};// Internal recursive comparison function for `isEqual`.deepEq = function(a, b, aStack, bStack) {// Unwrap any wrapped objects.if (a instanceof _) a = a._wrapped;if (b instanceof _) b = b._wrapped;// Compare `[[Class]]` names.var className = toString.call(a);if (className !== toString.call(b)) return false;switch (className) {// Strings, numbers, regular expressions, dates, and booleans are compared by value.case '[object RegExp]':// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')case '[object String]':// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is// equivalent to `new String("5")`.return '' + a === '' + b;case '[object Number]':// `NaN`s are equivalent, but non-reflexive.// Object(NaN) is equivalent to NaN.if (+a !== +a) return +b !== +b;// An `egal` comparison is performed for other numeric values.return +a === 0 ? 1 / +a === 1 / b : +a === +b;case '[object Date]':case '[object Boolean]':// Coerce dates and booleans to numeric primitive values. Dates are compared by their// millisecond representations. Note that invalid dates with millisecond representations// of `NaN` are not equivalent.return +a === +b;case '[object Symbol]':return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);}var areArrays = className === '[object Array]';if (!areArrays) {if (typeof a != 'object' || typeof b != 'object') return false;// Objects with different constructors are not equivalent, but `Object`s or `Array`s// from different frames are.var aCtor = a.constructor, bCtor = b.constructor;if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&_.isFunction(bCtor) && bCtor instanceof bCtor)&& ('constructor' in a && 'constructor' in b)) {return false;}}// Assume equality for cyclic structures. The algorithm for detecting cyclic// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.// Initializing stack of traversed objects.// It's done here since we only need them for objects and arrays comparison.aStack = aStack || [];bStack = bStack || [];var length = aStack.length;while (length--) {// Linear search. Performance is inversely proportional to the number of// unique nested structures.if (aStack[length] === a) return bStack[length] === b;}// Add the first object to the stack of traversed objects.
        aStack.push(a);bStack.push(b);// Recursively compare objects and arrays.if (areArrays) {// Compare array lengths to determine if a deep comparison is necessary.length = a.length;if (length !== b.length) return false;// Deep compare the contents, ignoring non-numeric properties.while (length--) {if (!eq(a[length], b[length], aStack, bStack)) return false;}} else {// Deep compare objects.var keys = _.keys(a), key;length = keys.length;// Ensure that both objects contain the same number of properties before comparing deep equality.if (_.keys(b).length !== length) return false;while (length--) {// Deep compare each memberkey = keys[length];if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;}}// Remove the first object from the stack of traversed objects.
        aStack.pop();bStack.pop();return true;};// Perform a deep comparison to check if two objects are equal._.isEqual = function(a, b) {return eq(a, b);};

View Code

转载于:https://www.cnblogs.com/etianqq/p/6192988.html

JavaScript中对象的比较相关推荐

  1. JavaScript中对象(Object)的方法

    JavaScript中对象方法总结: 资料来源:网道-互联网开发文档 [https://wangdoc.com/] 1.Object.getPrototypeOf(Object) Object.get ...

  2. javascript中对象_了解JavaScript中的承诺

    javascript中对象 我向您承诺,到本文结束时,您将更好地了解JavaScript. 我与JavaScript有一种"爱与恨"的关系. 但是尽管如此,JavaScript一直 ...

  3. 删除javaScript中对象的属性

    删除javaScript中对象的属性 语法 delete 对象.属性;

  4. javascript中对象的assign()方法

    javascript中对象的assign()方法 Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.它将返回目标对象. 语法: Object.assign( ...

  5. JavaScript 中对象的属性类型

    对象的属性类型 JavaScript 中的对象的属性包括数据属性和访问器属性,在 JavaScript 引擎的内部实现中定义了用于描述属性(property)的特性(attribute).规范中将特性 ...

  6. javascript中对象、JSON格式数据、创建对象的方式、数据类型分类及特点

    对象 对象指:具体的一个实物,javascript中对象是指一组没有顺序的属性和方法的集合,所有的事物都是对象,例如:函数,数组,字符串等.属性指事物的特征,一般为名词表示:方法指对象的行为,一般用动 ...

  7. javascript 无法修改 数组中对象_谈谈JavaScript中对象建立(Object)

    在这篇文章中我将会着重说明如何创建JavaScript里的对象(Object). 对象(Object)是什么? 在开始介绍如何创建对象前,我们要知道对象是什么.对象(Object)简单地来说,就是一堆 ...

  8. JavaScript中对象数据存储

    JS中对象数据存储 对象数据存储在堆栈中.栈的数据读取,写入速度快,但是存储的内容较少.堆的读取和写入速度慢,但是存储的内容多.举个例子来说就像电脑中内存和硬盘,内存就像栈,需要经常获取,写入速度比较 ...

  9. js的object的key需要引号吗,JavaScript中对象是否需要加引号?

    对象的属性名是包括空字符串在内的所有字符串. 那么问题来了,我们平时定义的对象如下,是没有引号""or''的,这样不加引号有没有错呢? 答案是,加不加分情况!但加了肯定没问题... ...

  10. 细说JavaScript中对象的属性和方法

    最近在回家的路上读了尼古拉斯的新书<JavaScript面向对象精要>,发现自己对对象的属性和方法不是很熟悉,特别是es5新增的部分,特写此文总结一下,同时也与大家共勉. 本文分为两部分, ...

最新文章

  1. Tcl学习之--列表|字典
  2. oracle日志分析产品,鼎甲技术应用:Oracle日志分析 之事务级精准恢复
  3. apmserv mysql密码_apmserv中修改mysql的root与phpmyadmin密码方法介绍_PHP教程
  4. mybatis15 mapper方式 代码
  5. 二叉搜索树的插入与删除(C语言)
  6. SVM 超平面方程
  7. 【软件工程导论】期末复习试题集
  8. PSP1000/2000/3000 PSPgo全主机介绍(2)
  9. TongWeb7本地部署(Windows)
  10. jQuery设置下拉框select 默认选中第一个option
  11. Knockout开发中文API系列1
  12. CAB 写inf文件
  13. 文件共享 无法访问,你可能没有权限使用网络资源,请与这台服务器的管理员联...
  14. python中三元运算符_Python中三元表达式的几种写法介绍
  15. 布同:如何循序渐进学习Python语言(转载)
  16. 带你玩转以太坊智能合约的Hello World
  17. go语言实现2048小游戏(完整代码)
  18. 仓库标准作业流程与WMS系统规划
  19. Centos7 Python3.6+Qt5.12.9+ PyQt5.12+Sip v5+QScintilla-2.10+Eric6
  20. access里的多步oledb错误_(ADO) 的 ConnectionString 属性 - SQL Server | Microsoft Docs

热门文章

  1. mysql has gone away 自动连接_MySQL-出现 MySQL server has gone away 原因和解决方法
  2. Python 语言程序设计(4-2)分支循环--无限循环
  3. python连接sqlserver_python连接SQL Server数据库
  4. java 子类 同名参数_Java -- 父类和子类拥有同名变量
  5. html一边自动宽度,有2列,希望右侧固定宽度,左侧自动宽度。_html/css_WEB-ITnose...
  6. 2022年考研计算机组成原理_2 数据表示和运算
  7. python 字符串替换_python字符串替换的2种方法
  8. 计算机硬件中板卡目前设备有哪几种,呼叫中心所需的硬件设备都有哪些?
  9. emui内核支持kvm吗_Linux专题—使用kvm搭建虚拟机
  10. 【李宏毅机器学习】04:梯度下降Gradient Descent