<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          分享 20 個 JS 工具函數(shù),提升你的開發(fā)效率

          共 21809字,需瀏覽 44分鐘

           ·

          2023-10-23 15:05

          前言

          日常開發(fā)中,面對各種不同的需求,我們經(jīng)常會用到以前開發(fā)過的一些工具函數(shù),把這些工具函數(shù)收集起來,將大大提高我們的開發(fā)效率。

          1、校驗數(shù)據(jù)類型

          export const typeOf = function(obj{
            return Object.prototype.toString.call(obj).slice(8-1).toLowerCase()
          }
          復(fù)制代碼

          示例:

          typeOf('樹哥')  // string
          typeOf([])  // array
          typeOf(new Date())  // date
          typeOf(null// null
          typeOf(true// boolean
          typeOf(() => { }) // function
          復(fù)制代碼

          2、防抖

          export const debounce = (() => {
            let timer = null
            return (callback, wait = 800) => {
              timer&&clearTimeout(timer)
              timer = setTimeout(callback, wait)
            }
          })()
          復(fù)制代碼

          示例:

          如 vue 中使用

          methods: {
            loadList() {
              debounce(() => {
                console.log('加載數(shù)據(jù)')
              }, 500)
            }
          }
          復(fù)制代碼

          3、節(jié)流

          export const throttle = (() => {
            let last = 0
            return (callback, wait = 800) => {
              let now = +new Date()
              if (now - last > wait) {
                callback()
                last = now
              }
            }
          })()
          復(fù)制代碼

          4、手機(jī)號脫敏

          export const hideMobile = (mobile) => {
            return mobile.replace(/^(\d{3})\d{4}(\d{4})$/"$1****$2")
          }
          復(fù)制代碼

          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()
            }
          }
          復(fù)制代碼

          6、關(guān)閉全屏

          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()
            }
          }
          復(fù)制代碼

          7、大小寫轉(zhuǎn)換

          參數(shù):

          • str 待轉(zhuǎn)換的字符串
          • 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.substr(1).toLowerCase() // substr 已不推薦使用
                return str[0].toUpperCase() + str.substring(1).toLowerCase()
              default:
                return str
            }
          }
          復(fù)制代碼

          示例:

          turnCase('vue'1// VUE
          turnCase('REACT'2// react
          turnCase('vue'3// Vue
          復(fù)制代碼

          8、解析URL參數(shù)

          export const getSearchParams = () => {
            const searchPar = new URLSearchParams(window.location.search)
            const paramsObj = {}
            for (const [key, value] of searchPar.entries()) {
              paramsObj[key] = value
            }
            return paramsObj
          }
          復(fù)制代碼

          示例:

          // 假設(shè)目前位于 https://****com/index?id=154513&age=18;
          getSearchParams(); // {id: "154513", age: "18"}
          復(fù)制代碼

          9、判斷手機(jī)是Andoird還是IOS

          /** 
           * 1: ios
           * 2: android
           * 3: 其它
           */

          export const getOSType=() => {
            let u = navigator.userAgent, app = navigator.appVersion;
            let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
            let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
            if (isIOS) {
              return 1;
            }
            if (isAndroid) {
              return 2;
            }
            return 3;
          }
          復(fù)制代碼

          10、數(shù)組對象根據(jù)字段去重

          參數(shù):

          • arr 要去重的數(shù)組
          • key 根據(jù)去重的字段名
          export const uniqueArrayObject = (arr = [], key = 'id') => {
            if (arr.length === 0return
            let list = []
            const map = {}
            arr.forEach((item) => {
              if (!map[item[key]]) {
                map[item[key]] = item
              }
            })
            list = Object.values(map)

            return list
          }
          復(fù)制代碼

          示例:

          const responseList = [
              { id1name'樹哥' },
              { id2name'黃老爺' },
              { id3name'張麻子' },
              { id1name'黃老爺' },
              { id2name'張麻子' },
              { id3name'樹哥' },
              { id1name'樹哥' },
              { id2name'黃老爺' },
              { id3name'張麻子' },
          ]

          uniqueArrayObject(responseList, 'id')
          // [{ id: 1, name: '樹哥' },{ id: 2, name: '黃老爺' },{ id: 3, name: '張麻子' }]
          復(fù)制代碼

          11、滾動到頁面頂部

          export const scrollToTop = () => {
            const height = document.documentElement.scrollTop || document.body.scrollTop;
            if (height > 0) {
              window.requestAnimationFrame(scrollToTop);
              window.scrollTo(0, height - height / 8);
            }
          }
          復(fù)制代碼

          12、滾動到元素位置

          export const smoothScroll = element =>{
              document.querySelector(element).scrollIntoView({
                  behavior'smooth'
              });
          };
          復(fù)制代碼

          示例:

          smoothScroll('#target'); // 平滑滾動到 ID 為 target 的元素
          復(fù)制代碼

          13、uuid

          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)
          }
          復(fù)制代碼

          示例:

          uuid() // a640be34-689f-4b98-be77-e3972f9bffdd
          復(fù)制代碼

          不過要吐槽一句的是,uuid一般應(yīng)由后端來進(jìn)行生成

          14、金額格式化

          參數(shù):

          • {number} number:要格式化的數(shù)字
          • {number} decimals:保留幾位小數(shù)
          • {string} dec_point:小數(shù)點(diǎn)符號
          • {string} thousands_sep:千分位符號
          export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
            number = (number + '').replace(/[^0-9+-Ee.]/g'')
            const n = !isFinite(+number) ? 0 : +number
            const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
            const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
            const dec = typeof dec_point === 'undefined' ? '.' : dec_point
            let s = ''
            const toFixedFix = function(n, prec{
              const k = Math.pow(10, prec)
              return '' + Math.ceil(n * k) / k
            }
            s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
            const re = /(-?\d+)(\d{3})/
            while (re.test(s[0])) {
              s[0] = s[0].replace(re, '$1' + sep + '$2')
            }

            if ((s[1] || '').length < prec) {
              s[1] = s[1] || ''
              s[1] += new Array(prec - s[1].length + 1).join('0')
            }
            return s.join(dec)
          }
          復(fù)制代碼

          示例:

          moneyFormat(10000000// 10,000,000.00
          moneyFormat(100000003'.''-'// 10-000-000.000
          復(fù)制代碼

          15、存儲操作

          class MyCache {
            constructor(isLocal = true) {
              this.storage = isLocal ? localStorage : sessionStorage
            }

            setItem(key, value) {
              if (typeof (value) === 'object') value = JSON.stringify(value)
              this.storage.setItem(key, value)
            }

            getItem(key) {
              try {
                return JSON.parse(this.storage.getItem(key))
              } catch (err) {
                return this.storage.getItem(key)
              }
            }

            removeItem(key) {
              this.storage.removeItem(key)
            }

            clear() {
              this.storage.clear()
            }

            key(index) {
              return this.storage.key(index)
            }

            length() {
              return this.storage.length
            }
          }

          const localCache = new MyCache()
          const sessionCache = new MyCache(false)

          export { localCache, sessionCache }
          復(fù)制代碼

          示例:

          localCache.getItem('user')
          sessionCache.setItem('name','樹哥')
          sessionCache.getItem('token')
          localCache.clear()
          復(fù)制代碼

          16、下載文件

          參數(shù):

          • api 接口
          • params 請求參數(shù)
          • fileName 文件名
          const downloadFile = (api, params, fileName, type = 'get') => {
            axios({
              method: type,
              url: api,
              responseType'blob'
              params: params
            }).then((res) => {
              let str = res.headers['content-disposition']
              if (!res || !str) {
                return
              }
              let suffix = ''
              // 截取文件名和文件類型
              if (str.lastIndexOf('.')) {
                fileName ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 1, str.lastIndexOf('.')))
                suffix = str.substring(str.lastIndexOf('.'), str.length)
              }
              //  如果支持微軟的文件下載方式(ie10+瀏覽器)
              if (window.navigator.msSaveBlob) {
                try {
                  const blobObject = new Blob([res.data]);
                  window.navigator.msSaveBlob(blobObject, fileName + suffix);
                } catch (e) {
                  console.log(e);
                }
              } else {
                //  其他瀏覽器
                let url = window.URL.createObjectURL(res.data)
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', fileName + suffix)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(link.href);
              }
            }).catch((err) => {
              console.log(err.message);
            })
          }`
          復(fù)制代碼

          使用:

          downloadFile('/api/download', {id}, '文件名')
          復(fù)制代碼

          17、時間操作

          關(guān)于時間操作,沒必要自己再寫一大串代碼了,強(qiáng)烈推薦使用 day.js[2]

          Day.js 是一個僅 2kb 大小的輕量級 JavaScript 時間日期處理庫,下載、解析和執(zhí)行的JavaScript更少,為代碼留下更多的時間。

          18、深拷貝

          export const clone = parent => {
            // 判斷類型
            const isType = (obj, type) => {
              if (typeof obj !== "object"return false;
              const typeString = Object.prototype.toString.call(obj);
              let flag;
              switch (type) {
                case "Array":
                  flag = typeString === "[object Array]";
                  break;
                case "Date":
                  flag = typeString === "[object Date]";
                  break;
                case "RegExp":
                  flag = typeString === "[object RegExp]";
                  break;
                default:
                  flag = false;
              }
              return flag;
            };

            // 處理正則
            const getRegExp = re => {
              var flags = "";
              if (re.global) flags += "g";
              if (re.ignoreCase) flags += "i";
              if (re.multiline) flags += "m";
              return flags;
            };
            // 維護(hù)兩個儲存循環(huán)引用的數(shù)組
            const parents = [];
            const children = [];

            const _clone = parent => {
              if (parent === nullreturn null;
              if (typeof parent !== "object"return parent;

              let child, proto;

              if (isType(parent, "Array")) {
                // 對數(shù)組做特殊處理
                child = [];
              } else if (isType(parent, "RegExp")) {
                // 對正則對象做特殊處理
                child = new RegExp(parent.source, getRegExp(parent));
                if (parent.lastIndex) child.lastIndex = parent.lastIndex;
              } else if (isType(parent, "Date")) {
                // 對Date對象做特殊處理
                child = new Date(parent.getTime());
              } else {
                // 處理對象原型
                proto = Object.getPrototypeOf(parent);
                // 利用Object.create切斷原型鏈
                child = Object.create(proto);
              }

              // 處理循環(huán)引用
              const index = parents.indexOf(parent);

              if (index != -1) {
                // 如果父數(shù)組存在本對象,說明之前已經(jīng)被引用過,直接返回此對象
                return children[index];
              }
              parents.push(parent);
              children.push(child);

              for (let i in parent) {
                // 遞歸
                child[i] = _clone(parent[i]);
              }

              return child;
            };
            return _clone(parent);
          };

          復(fù)制代碼

          此方法存在一定局限性:一些特殊情況沒有處理: 例如Buffer對象、Promise、Set、Map。

          如果確實(shí)想要完備的深拷貝,推薦使用 lodash 中的 cloneDeep 方法。

          19、模糊搜索

          參數(shù):

          • list 原數(shù)組
          • keyWord 查詢的關(guān)鍵詞
          • attribute 數(shù)組需要檢索屬性
          export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
            const reg = new RegExp(keyWord)
            const arr = []
            for (let i = 0; i < list.length; i++) {
              if (reg.test(list[i][attribute])) {
                arr.push(list[i])
              }
            }
            return arr
          }
          復(fù)制代碼

          示例:

          const list = [
            { id1name'樹哥' },
            { id2name'黃老爺' },
            { id3name'張麻子' },
            { id4name'湯師爺' },
            { id5name'胡萬' },
            { id6name'花姐' },
            { id7name'小梅' }
          ]
          fuzzyQuery(list, '樹''name'// [{id: 1, name: '樹哥'}]
          復(fù)制代碼

          20、遍歷樹節(jié)點(diǎn)

          export const foreachTree = (data, callback, childrenName = 'children') => {
            for (let i = 0; i < data.length; i++) {
              callback(data[i])
              if (data[i][childrenName] && data[i][childrenName].length > 0) {
                foreachTree(data[i][childrenName], callback, childrenName)
              }
            }
          }
          復(fù)制代碼

          示例:

          假設(shè)我們要從樹狀結(jié)構(gòu)數(shù)據(jù)中查找 id 為 9 的節(jié)點(diǎn)

          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"}   
          復(fù)制代碼

          ---END---

          來自:掘金,作者:嗆再首

          鏈接:https://juejin.cn/post/7132714583399071758



          瀏覽 318
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天天干狠狠操 | 91黄页免费观看视频 | 欧美成人乱码视频 | 操逼国产网站 | 欧美亚洲俺也去欧美 |