常用的js工具函数总结

81 阅读2分钟

1.数据类型校验

export const typeOf = function(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

示例

typeOf('锄禾日当午')   *// string*

*typeOf(111)    //  number*

typeOf(null)  *// null*

typeOf(undefined) // undefined

typeOf(true)  *// boolean*

typeOf(() => { })  *// function*

typeOf([])  // array typeOf(new Date())  // date

2.防抖

image.png

export const debounce = (() => {

  let timer = null

  return (callback, wait = 800) => {

      timer&&clearTimeout(timer)

      timer = setTimeout(callback, wait)

  }

})()

3.节流

export const throttle = (() => {

  let last = 0

  return (callback, wait = 800) => {

    let now = new Date()

    if (now - last > wait) {

      callback()

      last = now

    }

  }

})()

类比:上厕所!!![我们理想化平均每个人完成上厕所的时间一样等于5分钟]

image.png

4.手机号脱敏

export const hideMobile = (mobile) => {

  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/"$1****$2")

}

5.开启全屏

export const launchFullscreen = (element) => {

  if (element.requestFullscreen) {

       element.requestFullscreen()

  } else if (element.mozRequestFullScreen) {

       element.mozRequestFullScreen()

  } else if (element.msRequestFullscreen) {

       element.msRequestFullscreen()

  } else if (element.webkitRequestFullscreen) {

       element.webkitRequestFullScreen()

  }

}

6.关闭全屏

export const exitFullscreen = () => {

  if (document.exitFullscreen) {

           document.exitFullscreen()

  } else if (document.msExitFullscreen) {

           document.msExitFullscreen()

  } else if (document.mozCancelFullScreen) {

           document.mozCancelFullScreen()

  } else if (document.webkitExitFullscreen) {

           document.webkitExitFullscreen()

  }

}

7.大小写转换

str 待转换的字符串 type 1-全大写 2-全小写 3-首字母大写

  


export const turnCase = (str, type) => {

  switch (type) {

    case 1:

      return str.toUpperCase()

    case 2:

      return str.toLowerCase()

    case 3:

      return str[0].toUpperCase() + str.substring(1).toLowerCase()

    default:

      return str

  }

}

8.解析URL参数

export const getSearchParams = () => {

  const searchPar = new URLSearchParams(window.location.search)

  const paramsObj = {}

  for (const [key, value] of searchPar.entries()) {

        paramsObj[key] = value

  }

  return paramsObj

}

示例:

*// 假设目前位于 https://***com/index?id=154513&age=18;

getSearchParams(); 

// {id: "154513", age: "18"}

9.对象数组根据字段去重

示例:

const responseList = [

    { id: 1, name: '张三' },

    { id: 2, name: '李四' },

    { id: 3, name: '王五' },

    { id: 1, name: '李四' },

    { id: 2, name: '张三' },

    { id: 3, name: '李四' },

    { id: 1, name: '王五' },

    { id: 2, name: '王五' },

    { id: 3, name: '张三' },

]

uniqueArrayObject(responseList, 'id')

// [{ id: 1, name: '张三' },{ id: 2, name: '李四' },{ id: 3, name: '王五' }]

image.png

10.滚动到页面顶部

export const scrollToTop = () => {

  const height = document.documentElement.scrollTop || document.body.scrollTop;

  if (height > 0) {

    window.requestAnimationFrame(scrollToTop);

    window.scrollTo(0, height - height / 8);

  }

}

11.滚动到元素位置

export const smoothScroll = element =>{

    document.querySelector(element).scrollIntoView({

        behavior'smooth'

    });

};

  


  


示例:

smoothScroll('#target');  *// 平滑滚动到 ID 为 target 的元素*

12.生成uuid

科普一下"URL.createObjectURL"===>https://juejin.cn/post/7043990457117835271

export const uuid = () => {

  const temp_url = URL.createObjectURL(new Blob())

  const uuid = temp_url.toString()

  URL.revokeObjectURL(temp_url)  *//释放这个url*

  return uuid.substring(uuid.lastIndexOf('/') + 1)

}

13.遍历树节点

假设我们要从树状结构数据中查找 id 为 9 的节点

const treeData = [{

  id1,

  label'一级 1',

  children: [{

    id4,

    label'二级 1-1',

    children: [{

      id9,

      label'三级 1-1-1'

    }, {

      id10,

      label'三级 1-1-2'

    }]

  }]

 }, {

  id2,

  label'一级 2',

  children: [{

    id5,

    label'二级 2-1'

  }, {

    id6,

    label'二级 2-2'

  }]

  }, {

    id3,

    label'一级 3',

    children: [{

      id7,

      label'二级 3-1'

    }, {

      id8,

      label'二级 3-2'

    }]

}],

  


let result

foreachTree(data, (item) => {

  if (item.id === 9) {

    result = item

  }

})

  


console.log('result', result)   *// {id: 9,label: "三级 1-1-1"}*

image.png

14.金额格式化

{number} number:要格式化的数字

{number} decimals:保留几位小数

{string} dec_point:小数点符号 {string}

thousands_sep:千分位符号

image.png

更多学习视频学习资料请参考:B站搜索“我们一起学前端”  

我们一起学前端的个人空间_哔哩哔哩_Bilibili