00 vue源码里面常见方法

 function isDefined (val) {
    return val !== undefined && val !== null
  }

  function isUnDefined (val) {
    return val === undefined || val === null
  }
  // eslint-disable-next-line no-unused-vars
  function primitive (val) {
    if (val === undefined || val === null) return false
    const primitiveArr = ['number', 'string', 'boolean', 'symbol']
    const type = typeof val
    return primitiveArr.includes(type)
  }
  // console.log([12, 'aa', true, null, undefined].map(primitive))

  function isObject (obj) {
    return obj !== null && typeof obj === 'object'
  }

  function isObject1 (obj) {
    return obj instanceof Object && typeof obj !== 'function'
  }
  // console.log([12, 'aa', true, null, undefined, {}, [], function () {}].map(isObject))
  // console.log([12, 'aa', true, null, undefined, {}, [], function () {}].map(isObject1))

  function toRawType (val) {
    const res = Object.prototype.toString.call(val) // ['[object Number]','[object String]','[object Boolean]', '[object Null]','[object Undefined]','[object Object]','[object Array]','[object Function]']
    return res.slice(8, -1) // slice 和substring都是通过索引截取字符串 但是slice更加强大 可以传入负值 表示倒数截取。建议通通用slice
  }
  // console.log([12, 'aa', true, null, undefined, {}, [], function () {}].map(toRawType))
  function isPromise (val) {
    return isDefined(val) && typeof val.then === 'function' && typeof val.catch === 'function'
  }
  // 用于将输入框input值尝试转为数字类型
  function toNumber (val) {
    const n = parseFloat(val) // 给定值被解析成浮点数number。如果给定值不能被转换成数值,则会返回 NaN。NaN typeof NaN=number NaN 的值表示不是一个数字
    return isNaN(n) ? val : n
  }
  console.log(['12', '12.12', 23, 'aa', true, {
    name: 'zs'
  }, null].map(toNumber))

  function cached (fn) {
    const obj = Object.create(null)
    return (...args) => {
      const key = JSON.stringify(args)
      obj[key] = obj[key] || fn(...args)
      return obj[key]
    }
  }
  // 类数组转为数组
  function toArray (likeArr, start = 0) {
    const length = likeArr.length - start
    let index = 0
    const ret = new Array(length) // 创建一个和类数组对象等长度的数组 初始值都是undefiend
    while (index !== length) {
      ret[index] = likeArr[start]
      start++
      index++
    }
    return ret
  }
  console.log(toArray({
    0: 42,
    1: 52,
    2: 63,
    3: 100,
    length: 4
  }))
  console.log(Array.from({
    0: 42,
    1: 52,
    2: 63,
    3: 100,
    length: 4
  }))

  function once (fn) {
    let flag = true
    return (...args) => {
      if (flag) {
        flag = false
        return fn(...args)
      }
    }
  }

  function fn1 (a) {
    return a
  }
  const onceFn1 = once(fn1)
原文地址:https://www.cnblogs.com/xiaoliziaaa/p/14154846.html