判断是否是类数组

/**
 * 检查value是否是类数组,如果一个值被认为是类数组,那么它不是一个函数,并且value.length是个整数,大于等于0,小于或等于 Number.MAX_SAFE_INTEGER
 * Checks if `value` is array-like. A value is considered array-like if it's not a function and
 * has a `value.length` that's an integer greater than or equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`
 * @param {*} value The value to check
 * @returns {boolean} Returns `true` if `value` is array-like, else false
 * @example
 *
 * isArrayLike([1, 2, 3])
 * // => true
 *
 * isArrayLike(document.body.children)
 * // => true
 *
 * isArrayLike('abc')
 * // => true
 *
 * isArrayLike(()=>{})
 * // => false
 */


const funcTag = "[object Function]"
const genTag = "[object GeneratorFunction]"
const asyncTag = "[object AsyncFunction]"
 
function isObject(value) {
  var type = typeof value
  return value != null && (type === "object" || type === "function")
}
 
function baseGetTag(value) {
  //在任何值上调用Object原生的toString()方法,都会返回一个[Object NativeConstructorName] 格式的字符串。
  //每个类在内部都有一个[[Class]]属性,这个属性中就指定了上述字符串中的构造函数名
  return Object.prototype.toString.call(value)
}
 
function isFunction(value) {
  if (!isObject) {
    return false
  }
 
  var tag = baseGetTag(value)
  return tag === funcTag || tag === genTag || tag === asyncTag
}

function isLength(value) {
  return (
    typeof value == "number" &&
    value > -1 &&
    value % 1 === 0 &&
    value <= MAX_SAFE_INTEGER
  )
}

function isArrayLike(value) {
  return value != null && !isFunction(value) && isLength(value.length)
}

export default isArrayLike

 

你可能感兴趣的:(lodash)