devtools 判断类数组的方法

var obj = {
    '2': 3,
    '3': 4,
    'length': 2,
    'splice': Array.prototype.splice,
    'push': Array.prototype.push
}
obj.push(1)
obj.push(2)
console.log(obj)

如上题所示,输出结果为一个类数组

/**
     * @param {?Object} obj
     * @return {boolean}
     */
    function isArrayLike(obj) {
      if (!obj || typeof obj !== 'object')
        return false;
      try {
        if (typeof obj.splice === 'function') {
          const len = obj.length;
          return typeof len === 'number' && (len >>> 0 === len && (len > 0 || 1 / len > 0));
        }
      } catch (e) {
      }
      return false;
    }

判断的过程:

  1. 存在且是对象
  2. 对象上的splice 属性是函数类型
  3. 对象上有 length 属性且为正整数
posted @ 2019-07-22 10:37  来亦何哀  阅读(200)  评论(0编辑  收藏  举报