js判斷兩個對象的屬性和值是否一致

毫無疑問,js中的對象是引用類型的對象。咱們使用 == 或者 === 已經沒法判斷兩個對象的屬性和值是否相等。spa

 

code:(Fn)指針

// 對比兩個對象的值是否徹底相等 返回值 true/false
 isObjectValueEqual (a, b) { //取對象a和b的屬性名
      var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); //判斷屬性名的length是否一致
      if (aProps.length != bProps.length) { return false; } //循環取出屬性名,再判斷屬性值是否一致
      for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; },

驗證以上的方法:code

var obj1 = { name: "Benjamin", sex : "male"}; var obj2 = { name: "Benjamin", sex : "male"}; var obj3 = obj1;//obj1和ob3的指針指向了內存中的同一個地址
 console.log(isObjectValueEqual(obj1, obj2));//true
 console.log(obj1 == obj3);//Outputs: true
 console.log(obj1 === obj3);//Outputs: true
 console.log(obj2 == obj3);//Outputs: false
 console.log(obj2 === obj3);//Outputs: false

 

  1.   function isObjectValueEqual(a, b) {   
  2.  
     
  3.  
          //取對象a和b的屬性名
  4.  
     
  5.  
         var aProps = Object.getOwnPropertyNames(a);
  6.  
     
  7.  
         var bProps = Object.getOwnPropertyNames(b);
  8.  
     
  9.  
          //判斷屬性名的length是否一致
  10.  
     
  11.  
         if (aProps.length != bProps.length) {
  12.  
     
  13.  
             return  false;
  14.  
     
  15.  
        }
  16.  
     
  17.  
          //循環取出屬性名,再判斷屬性值是否一致
  18.  
     
  19.  
         for ( var i = 0; i < aProps.length; i++) {
  20.  
     
  21.  
             var propName = aProps[i];
  22.  
     
  23.  
             if (a[propName] !== b[propName]) {
  24.  
     
  25.  
                 return  false;
  26.  
     
  27.  
            }
  28.  
     
  29.  
        }
  30.  
     
  31.  
         return  true;
  32.  
     
  33.  
    }
相關文章
相關標籤/搜索