JavaScript中對象的比較

来源:http://www.cnblogs.com/etianqq/archive/2016/12/17/6192988.html
-Advertisement-
Play Games

Javascript中有'=='和' '兩種相等比較,後者是全等,會判斷數據類型,前者是相等,在比較時,會發生隱式轉換。 如果將兩個對象做'=='比較,結果會如何呢? 比如有如下兩個對象: 可以看到,哪怕兩個對象的屬性完全一樣,無論是'=='或者' ',返回都是false。 原因:對象通過指針指向的 ...


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 checks
        var 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 member
                key = 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

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 概述: Apache Solr是一個用JAVA語言構建在Apache Lucene項目上的開源的企業級搜索平臺。主要特性包含:全文搜索、命中高亮、片段式搜索、實時索引、動態集群、資料庫集成、NoSQL特性和富文本處理。提供分散式搜索和索引複製,設計時便充分考慮了擴展和容錯能力。Solr目前是第二流行 ...
  • 1、節選自Python Documentation 3.5.2的部分解釋 Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations ...
  • POI和Excel簡介 JAVA中操作Excel的有兩種比較主流的工具包: JXL 和 POI 。jxl 只能操作Excel 95, 97, 2000也即以.xls為尾碼的excel。而poi可以操作Excel 95及以後的版本,即可操作尾碼為 .xls(03版)和.xlsx(07版)兩種格式的ex ...
  • 編寫MyBatis配置文件(配置文件可以在上面下載的壓縮包root下找到PDF,裡面也有示例配置) Emp.xml 其中幾個常用的元素的作用如下:( 1.environment 和 2.mappers元素) 1.environment 元素:用於配置多個數據環境,這樣可以映射多個資料庫信息。採用de ...
  • java.lang.IncompatibleClassChangeError: Implementing class,用常見的解決問題的方法解決不常見的問題 ...
  • JavaScript的數組,相比其他語言,是比較特殊的。數組是Object類型,只不過,有幾個比較特殊的地方: 可以看到,如果不指定key值,數組會自動添加預設索引下標值,將其作為key。 這種情況下,length又是如何計算的呢? 從上面的代碼可以看出,length值是根據最大的索引下標計算的,也 ...
  • 看看變數類型,也是學習任何一門編程語言都必須要面對的重點知識 ...
  • 1.功能 解決javascript回調地獄 安裝eventProxy 2.常用方法 ①解決回調方法 emit:觸發事件 after all:告訴它你要監聽哪些事件,並給它一個回調函數。ep.all('event1', 'event2', function (result1, result2) {}) ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...