簡易Api

Genus_發表於2020-12-31

一些簡單的方法~~

  • 判斷是否為 promise
  function isPromise(val){
    return val && typeof val.then ==='function'
  }
  • 是否為物件
function isObeject(obj) {
  return obj != null && typeof obj === "object"
}
  • 首字母大寫
function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
  }
  • 10000 => “10,000”
function toThousandFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
  • 拿到物件的鍵和值
 function forEachValue (obj) {
    Object.keys(obj).forEach(key => {
      console.log(obj[key]);  //obj[key]就是物件的鍵和值
    })
  }

  function forEachValue (obj, fn) {
  Object.keys(obj).forEach(key => fn(obj[key], key))
}
  • 深拷貝
function deepCopy (obj, cache = []) {
  //如果不是物件或陣列 則返回
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

 //如果是物件或陣列
  const hit = find(cache, c => c.original === obj)
  if (hit) {
    return hit.copy
  }

 //判斷是陣列還是物件
  const copy = Array.isArray(obj) ? [] : {}
  cache.push({
    original: obj,
    copy
  })

  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache)
  })

  return copy
}