【適合收藏】讓你減少加班的15條高效JS技巧!

陳大魚頭發表於2020-04-06

魚頭辛苦總結的15條非常高效的JS技巧,掌握這15個JS技巧,讓你減少加班次數,多抽出點時間來陪女(男)朋友。

正文

延遲函式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秒
複製程式碼

分割指定長度的元素陣列

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)) // []
複製程式碼

獲取陣列交集

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])) // []
複製程式碼

函式柯里化

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]
複製程式碼

字串前面空格去除與替換

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

字串後面空格去除與替換

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

獲取當前子元素是其父元素下子元素的排位

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

獲取當前元素相對於document的偏移量

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

獲取元素型別

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

判斷是否是移動端

const isMobile = () => 'ontouchstart' in window
複製程式碼

fade動畫

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()
}
複製程式碼

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

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 (中國標準時間)
複製程式碼

禁止網頁複製貼上

const html = document.querySelector('html')
html.oncopy = () => false
html.onpaste = () => false
複製程式碼

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)
}
複製程式碼

去除字串中的html程式碼

const removeHTML = (str = '') => str.replace(/<[\/\!]*[^<>]*>/ig, '')
console.log(removeHTML('<h1>哈哈哈哈<呵呵呵</h1>')) // 哈哈哈哈<呵呵呵
複製程式碼

後記

如果你喜歡探討技術,或者對本文有任何的意見或建議,非常歡迎加魚頭微信好友一起探討,當然,魚頭也非常希望能跟你一起聊生活,聊愛好,談天說地。 魚頭的微訊號是:krisChans95 也可以掃碼關注公眾號,訂閱更多精彩內容。

https://user-gold-cdn.xitu.io/2020/3/29/17125f34bff387d7?w=1000&h=480&f=png&s=311000

相關文章