Javascript获取属性的值以及比较值

       这几天遇到一个比较两个对象中属性值是否相等的问题。写了一个比较函数,如下:

function isObjectValueEqual(a, b) {

    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    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;
}
这里使用了Object.getOwnPropertyByNames(obj)这个函数。该方法返回一个由指定对象的所有 自身属性的属性名(包括不可枚举属性)组成的数组,但是不会获取到原型链上的属性。这个方法在IE8下测试时发现不兼容。

       准备用最原始的for-in遍历对象属性,但是这样的话for-in还会遍历出一个对象从其原型链上继承到的可枚举属性。

       可是我需要一个一个对象的所有属性,包括不可枚举的。看到还有一个Object.keys(),它也是从IE9开始才支持。最后写了一个兼容IE8的Object.keys函数,如下:

Object.keys = Object.keys || function(obj){
    if (obj !== Object(obj)){
        return;
    }
    var arr = [];
    for(var i in obj){
        //obj.hasOwnProperty(属性)  检测对象在排除原型链的情况下是否具有某个属性。
        // if(obj.hasOwnProperty(i)){
        if(Object.prototype.hasOwnProperty.call(obj,i)){
            arr.push(i)
        }
    }
    return arr;
 };
上面的获取对象属性值得方法即为:

var aprops = Object.keys(a);
       在IE8下测试时,又发现一个情况:
//屏蔽(覆盖)不可枚举的方法 toString()
var obj = {
    toString:"ok"
}
for(var i in obj){
    if(i === "toString"){
        alert(obj[i]);//IE中不会弹出 "ok"
    }
}
      原来是IE8等早期浏览器的BUG,屏蔽了(即覆盖)原型中不可枚举属性的实例属性也会在for-in循环中返回。因为只要是开发人员定义的属性都是可以枚举的,即使覆盖了原型中原来不可以枚举的属性,但是IE8及早期版本不买账。

      那么这个bug会影响哪些属性和方法呢,包括toString()在内的以下七种:hasOwnProperty(),propertyIsEnumerable(),toLocaleString(),toString(),valueOf(),isPrototypeOf,constructor。

参考的实现如下:

if (!Object.keys) {
  Object.keys = (function () {
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;
    return function (obj) {
      if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
      var result = [];
      for (var prop in obj) {
        if (hasOwnProperty.call(obj, prop)) result.push(prop);
      }
      if (hasDontEnumBug) {
        for (var i=0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
        }
      }
      return result;
    }
  })()
};
最主要的是 hasDontEnumBug = !({toString: null}).propertyIsEnumerable(‘toString’).
首先屏蔽了创建对象 {toString:null} 用来屏蔽(覆盖)原型中不可枚举的toString()方法,即hasDontEnumBug为true时则为IE8及以下浏览器,然后进行数组push即可:

上面的代码在IE7(也许IE8也是)下有个问题,就是如果传入一个来自其他 window 对象下的对象时,不可枚举的属性也会获取到。 解决办法就是那就用window.frameElement判断是不是当前窗口:

if(window.frameElement == null && !Object.keys){
 //code
 }
其实上述还有很多的问题存在:

1) 如果该属性值之一本身就是一个对象
2) 如果属性值中的一个是NaN等等

所以最好是依赖完善的测试库来涵盖各种便捷情况,Underscore和Lo-Dash有一个名为_.isEqual()方法,用来比较好的处理深度对象的比较。

最后附上Underscore中isEqual的部分源码:

// Internal recursive comparison function for `isEqual`.
var 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;
  // A strict comparison is necessary because `null == undefined`.
  if (a == null || b == null) return a === b;
  // 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;
  }
  if (typeof a != 'object' || typeof b != 'object') 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`.
  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;
  }
  // Objects with different constructors are not equivalent, but `Object`s
  // from different frames are.
  var aCtor = a.constructor, bCtor = b.constructor;
  if (
    aCtor !== bCtor &&
    // Handle Object.create(x) cases
    'constructor' in a && 'constructor' in b &&
    !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
      _.isFunction(bCtor) && bCtor instanceof bCtor)
  ) {
    return false;
  }
  // Add the first object to the stack of traversed objects.
  aStack.push(a);
  bStack.push(b);
  var size, result;
  // Recursively compare objects and arrays.
  if (className === '[object Array]') {
    // Compare array lengths to determine if a deep comparison is necessary.
    size = a.length;
    result = size === b.length;
    if (result) {
      // Deep compare the contents, ignoring non-numeric properties.
      while (size--) {
        if (!(result = eq(a[size], b[size], aStack, bStack))) break;
      }
    }
  } else {
    // Deep compare objects.
    var keys = _.keys(a), key;
    size = keys.length;
    // Ensure that both objects contain the same number of properties before comparing deep equality.
    result = _.keys(b).length === size;
    if (result) {
      while (size--) {
        // Deep compare each member
        key = keys[size];
        if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
      }
    }
  }
  // Remove the first object from the stack of traversed objects.
  aStack.pop();
  bStack.pop();
  return result;
};

// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
  return eq(a, b, [], []);
};

参考:

https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/keys




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值