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

首頁 > 開發(fā) > JS > 正文

JS判斷兩個數(shù)組或?qū)ο笫欠裣嗤姆椒ㄊ纠?/h1>
2024-05-06 16:48:34
字體:
供稿:網(wǎng)友

本文實例講述了JS判斷兩個數(shù)組或?qū)ο笫欠裣嗤姆椒?。分享給大家供大家參考,具體如下:

JS 判斷兩個數(shù)組是否相同

要判斷2個數(shù)組是否相同,首先要把數(shù)組進(jìn)行排序,然后轉(zhuǎn)換成字符串進(jìn)行比較。

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

或者

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

經(jīng)驗證,上述方法對復(fù)雜數(shù)組結(jié)構(gòu)不適用。

JS 判斷兩個對象是否相同

這是網(wǎng)上某大神封裝對比對象是否相同的 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;};

經(jīng)檢測,同樣也不支持復(fù)雜數(shù)據(jù)結(jié)構(gòu)的對象。

一般情況下用的話上述2種方法已經(jīng)夠用了,拿來作比較的一般都是簡單的數(shù)據(jù)結(jié)構(gòu)。

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


注:相關(guān)教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

主站蜘蛛池模板: 聂荣县| 多伦县| 宿迁市| 淳化县| 常熟市| 惠来县| 石台县| 紫阳县| 桐庐县| 景东| 永康市| 西昌市| 荥经县| 区。| 花莲市| 平度市| 洪泽县| 礼泉县| 白城市| 阜阳市| 买车| 梅州市| 长子县| 鹿邑县| 昭通市| 信丰县| 阳西县| 九龙县| 永安市| 桦川县| 炎陵县| 东兴市| 岳阳市| 壶关县| 屏东市| 新郑市| 沙湾县| 齐河县| 南岸区| 宜君县| 紫阳县|