chunhuile / common

0 stars 0 forks source link

js object.keys的用法及兼容性 #8

Open chunhuile opened 2 months ago

chunhuile commented 2 months ago

定义:Object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组

兼容旧环境

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;
}

})() }; 额外判断对象的构造函数呢? js的9个内置函数

new Object();

new String(); new Number(); new Boolean(); new Array(); new RegExp(); new Function(); new Date(); new Error(); https://juejin.cn/post/6961926111907282951

公共方法

/**