国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JS判斷兩個數組或對象是否相同的方法示例

2019-11-19 12:03:48
字體:
來源:轉載
供稿:網友

本文實例講述了JS判斷兩個數組或對象是否相同的方法。分享給大家供大家參考,具體如下:

JS 判斷兩個數組是否相同

要判斷2個數組是否相同,首先要把數組進行排序,然后轉換成字符串進行比較。

JSON.stringify([1,2,3].sort()) === JSON.stringify([3,2,1].sort()); //true

或者

[1,2,3].sort().toString() === [3,2,1].sort().toString(); //true

經驗證,上述方法對復雜數組結構不適用。

JS 判斷兩個對象是否相同

這是網上某大神封裝對比對象是否相同的 function。

let cmp = ( x, y ) => {// If both x and y are null or undefined and exactly the same    if ( x === y ) {      return true;    }// If they are not strictly equal, they both need to be Objects    if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) {      return false;    }//They must have the exact same prototype chain,the closest we can do is//test the constructor.    if ( x.constructor !== y.constructor ) {      return false;    }    for ( var p in x ) {      //Inherited properties were tested using x.constructor === y.constructor      if ( x.hasOwnProperty( p ) ) {        // Allows comparing x[ p ] and y[ p ] when set to undefined        if ( ! y.hasOwnProperty( p ) ) {          return false;        }        // If they have the same strict value or identity then they are equal        if ( x[ p ] === y[ p ] ) {          continue;        }        // Numbers, Strings, Functions, Booleans must be strictly equal        if ( typeof( x[ p ] ) !== "object" ) {          return false;        }        // Objects and Arrays must be tested recursively        if ( ! Object.equals( x[ p ], y[ p ] ) ) {          return false;        }      }    }    for ( p in y ) {      // allows x[ p ] to be set to undefined      if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) {        return false;      }    }    return true;};

經檢測,同樣也不支持復雜數據結構的對象。

一般情況下用的話上述2種方法已經夠用了,拿來作比較的一般都是簡單的數據結構。

更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript數組操作技巧總結》、《JavaScript遍歷算法與技巧總結》、《javascript面向對象入門教程》、《JavaScript數學運算用法總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript錯誤與調試技巧總結

希望本文所述對大家JavaScript程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 吉首市| 车险| 儋州市| 社旗县| 永善县| 万盛区| 乌海市| 湘西| 玉龙| 桂平市| 灌南县| 大埔县| 东港市| 万源市| 工布江达县| 怀化市| 岳阳市| 阳谷县| 白城市| 内黄县| 延寿县| 巴林右旗| 芜湖县| 武邑县| 松桃| 嘉黎县| 霸州市| 贡嘎县| 鹿邑县| 安平县| 内黄县| 右玉县| 长丰县| 霞浦县| 甘南县| 许昌县| 修文县| 固安县| 左权县| 莎车县| 闽清县|