new Promise((resolve, reject) => setTimeout(resolve, ms)) const getData = status => new Promise((resolve, reject) => { status ? resolve('done') : reject('fail') })..." />
    1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        15條你可能不知道的JS高效技巧

        共 3868字,需瀏覽 8分鐘

         ·

        2020-08-13 00:31


        1、延遲函數(shù)delay

         const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms))  const getData = status => new Promise((resolve, reject) => {     status ? resolve('done') : reject('fail') }) const getRes = async (data) => {     try {         const res = await getData(data)         const timestamp = new Date().getTime()         await delay(1000)         console.log(res, new Date().getTime() - timestamp)     } catch (error) {         console.log(error)     } } getRes(true) // 隔了1秒

        2、分割指定長(zhǎng)度的元素?cái)?shù)組

         const listChunk = (list, size = 1, cacheList = []) => {     const tmp = [...list]     if (size <= 0) {         return cacheList     }     while (tmp.length) {         cacheList.push(tmp.splice(0, size))     }     return cacheList }  console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9])) // [[1], [2], [3], [4], [5], [6], [7], [8], [9]] console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]] console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], 0)) // [] console.log(listChunk([1, 2, 3, 4, 5, 6, 7, 8, 9], -1)) // []

        3、獲取數(shù)組交集

         const intersection = (list, ...args) => list.filter(item => args.every(list => list.includes(item)))  console.log(intersection([2, 1], [2, 3])) // [2] console.log(intersection([1, 2], [3, 4])) // []

        4、函數(shù)柯里化

         const curring = fn => {     const { length } = fn     const curried = (...args) => {         return (args.length >= length               ? fn(...args)               : (...args2) => curried(...args.concat(args2)))     }     return curried }  const listMerge = (a, b, c) => [a, b, c] const curried = curring(listMerge) console.log(curried(1)(2)(3)) // [1, 2, 3]  console.log(curried(1, 2)(3)) // [1, 2, 3]  console.log(curried(1, 2, 3)) // [1, 2, 3]

        5、字符串前面空格去除與替換

         const trimStart = str => str.replace(new RegExp('^([\\s]*)(.*)$'), '$2') console.log(trimStart(' abc ')) // abc console.log(trimStart('123 ')) // 123

        6、字符串后面空格去除與替換

         const trimEnd = str => str.replace(new RegExp('^(.*?)([\\s]*)$'), '$1') console.log(trimEnd(' abc ')) //   abc console.log(trimEnd('123 ')) // 123

        7、獲取當(dāng)前子元素是其父元素下子元素的排位

         const getIndex = el => {     if (!el) {         return -1     }     let index = 0     do {         index++     } while (el = el.previousElementSibling);     return index }

        8、獲取當(dāng)前元素相對(duì)于document的偏移量

         const getOffset = el => {     const {         top,         left     } = el.getBoundingClientRect()     const {         scrollTop,         scrollLeft     } = document.body     return {         top: top + scrollTop,         left: left + scrollLeft     } }

        9、獲取元素類(lèi)型

        const dataType = obj => Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();

        10、判斷是否是移動(dòng)端

         const isMobile = () => 'ontouchstart' in window

        11、fade動(dòng)畫(huà)

         const fade = (el, type = 'in') {     el.style.opacity = (type === 'in' ? 0 : 1)     let last = +new Date()     const tick = () => {         const opacityValue = (type === 'in'                              ? (new Date() - last) / 400                             : -(new Date() - last) / 400)         el.style.opacity = +el.style.opacity + opacityValue         last = +new Date()         if (type === 'in'           ? (+el.style.opacity < 1)           : (+el.style.opacity > 0)) {             requestAnimationFrame(tick)         }     }     tick() }?

        12、將指定格式的字符串解析為日期字符串

        const dataPattern = (str, format = '-') => {     if (!str) {         return new Date()     }     const dateReg = new RegExp(`^(\\d{2})${format}(\\d{2})${format}(\\d{4})$`)     const [, month, day, year] = dateReg.exec(str)     return new Date(`${month}, ${day} ${year}`) }  console.log(dataPattern('12-25-1995')) // Mon Dec 25 1995 00:00:00 GMT+0800 (中國(guó)標(biāo)準(zhǔn)時(shí)間)

        13、禁止網(wǎng)頁(yè)復(fù)制粘貼

         const html = document.querySelector('html') html.oncopy = () => false html.onpaste = () => false

        14、input框限制只能輸入中文

         const input = document.querySelector('input[type="text"]') const clearText = target => {     const {         value     } = target     target.value = value.replace(/[^\u4e00-\u9fa5]/g, '') } input.onfocus = ({target}) => {     clearText(target) } input.onkeyup = ({target}) => {     clearText(target) } input.onblur = ({target}) => {     clearText(target) } input.oninput = ({target}) => {     clearText(target) }

        15、去除字符串中的html代碼

         const removehtml = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '') console.log(removehtml('

        哈哈哈哈<呵呵呵

        '
        )) // 哈哈哈哈<呵呵呵

        瀏覽 17
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            三p被狂躁到高潮失禁 | 欧美成人精品一区二区三区免费 | 伦理片免费观看网站 | 亚洲人成免费 | 日韩欧美日韩欧美 | c逼网站| 久久肏屄视频 | 免费看日产一区二区三区 | 久久激情视频 | 欧美成人三级视频 |