dongtianqi/dtq-blog

js 类数组对象

Opened this issue · 0 comments

devtools 判断类数组的方法:

/**
 * @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;
}

判断的过程:

存在且是对象
对象上的splice 属性是函数类型
对象上有 length 属性且为正整数