溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

實(shí)用JavaScript代碼片段有哪些

發(fā)布時間:2021-09-10 11:06:20 來源:億速云 閱讀:128 作者:柒染 欄目:web開發(fā)

實(shí)用JavaScript代碼片段有哪些,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

1. 下載一個excel文檔

同時適用于word,ppt等瀏覽器不會默認(rèn)執(zhí)行預(yù)覽的文檔,也可以用于下載后端接口返回的流數(shù)據(jù),見3

//下載一個鏈接 
function download(link, name) {
    if(!name){
            name=link.slice(link.lastIndexOf('/') + 1)
    }
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
}
//下載excel
download('http://111.229.14.189/file/1.xlsx')

2. 在瀏覽器中自定義下載一些內(nèi)容

場景:我想下載一些DOM內(nèi)容,我想下載一個JSON文件

/**
 * 瀏覽器下載靜態(tài)文件
 * @param {String} name 文件名
 * @param {String} content 文件內(nèi)容
 */
function downloadFile(name, content) {
    if (typeof name == 'undefined') {
        throw new Error('The first parameter name is a must')
    }
    if (typeof content == 'undefined') {
        throw new Error('The second parameter content is a must')
    }
    if (!(content instanceof Blob)) {
        content = new Blob([content])
    }
    const link = URL.createObjectURL(content)
    download(link, name)
}
//下載一個鏈接
function download(link, name) {
    if (!name) {//如果沒有提供名字,從給的Link中截取最后一坨
        name =  link.slice(link.lastIndexOf('/') + 1)
    }
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.style.display = 'none'
    eleLink.href = link
    document.body.appendChild(eleLink)
    eleLink.click()
    document.body.removeChild(eleLink)
}

使用方式:

downloadFile('1.txt','lalalallalalla')
downloadFile('1.json',JSON.stringify({name:'hahahha'}))

3. 下載后端返回的流

數(shù)據(jù)是后端以接口的形式返回的,調(diào)用1中的download方法進(jìn)行下載

 download('http://111.229.14.189/gk-api/util/download?file=1.jpg')
 download('http://111.229.14.189/gk-api/util/download?file=1.mp4')

4. 提供一個圖片鏈接,點(diǎn)擊下載

圖片、pdf等文件,瀏覽器會默認(rèn)執(zhí)行預(yù)覽,不能調(diào)用download方法進(jìn)行下載,需要先把圖片、pdf等文件轉(zhuǎn)成blob,再調(diào)用download方法進(jìn)行下載,轉(zhuǎn)換的方式是使用axios請求對應(yīng)的鏈接

//可以用來下載瀏覽器會默認(rèn)預(yù)覽的文件類型,例如mp4,jpg等
import axios from 'axios'
//提供一個link,完成文件下載,link可以是  http://xxx.com/xxx.xls
function downloadByLink(link,fileName){
    axios.request({
        url: link,
        responseType: 'blob' //關(guān)鍵代碼,讓axios把響應(yīng)改成blob
    }).then(res => {
	const link=URL.createObjectURL(res.data)
        download(link, fileName)
    })

}

注意:會有同源策略的限制,需要配置轉(zhuǎn)發(fā)

5 防抖

在一定時間間隔內(nèi),多次調(diào)用一個方法,只會執(zhí)行一次.

這個方法的實(shí)現(xiàn)是從Lodash庫中copy的

/**
 *
 * @param {*} func 要進(jìn)行debouce的函數(shù)
 * @param {*} wait 等待時間,默認(rèn)500ms
 * @param {*} immediate 是否立即執(zhí)行
 */
export function debounce(func, wait=500, immediate=false) {
    var timeout
    return function() {
        var context = this
        var args = arguments

        if (timeout) clearTimeout(timeout)
        if (immediate) {
            // 如果已經(jīng)執(zhí)行過,不再執(zhí)行
            var callNow = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if (callNow) func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                func.apply(context, args)
            }, wait)
        }
    }
}

使用方式:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <input id="input" />
        <script>
            function onInput() {
                console.log('1111')
            }
            const debounceOnInput = debounce(onInput)
            document
                .getElementById('input')
                .addEventListener('input', debounceOnInput) //在Input中輸入,多次調(diào)用只會在調(diào)用結(jié)束之后,等待500ms觸發(fā)一次   
        </script>
    </body>
</html>

如果第三個參數(shù)immediate傳true,則會立即執(zhí)行一次調(diào)用,后續(xù)的調(diào)用不會在執(zhí)行,可以自己在代碼中試一下

6 節(jié)流

多次調(diào)用方法,按照一定的時間間隔執(zhí)行

這個方法的實(shí)現(xiàn)也是從Lodash庫中copy的

/**
 * 節(jié)流,多次觸發(fā),間隔時間段執(zhí)行
 * @param {Function} func
 * @param {Int} wait
 * @param {Object} options
 */
export function throttle(func, wait=500, options) {
    //container.onmousemove = throttle(getUserAction, 1000);
    var timeout, context, args
    var previous = 0
    if (!options) options = {leading:false,trailing:true}

    var later = function() {
        previous = options.leading === false ? 0 : new Date().getTime()
        timeout = null
        func.apply(context, args)
        if (!timeout) context = args = null
    }

    var throttled = function() {
        var now = new Date().getTime()
        if (!previous && options.leading === false) previous = now
        var remaining = wait - (now - previous)
        context = this
        args = arguments
        if (remaining <= 0 || remaining > wait) {
            if (timeout) {
                clearTimeout(timeout)
                timeout = null
            }
            previous = now
            func.apply(context, args)
            if (!timeout) context = args = null
        } else if (!timeout && options.trailing !== false) {
            timeout = setTimeout(later, remaining)
        }
    }
    return throttled
}

第三個參數(shù)還有點(diǎn)復(fù)雜,options

  • leading,函數(shù)在每個等待時延的開始被調(diào)用,默認(rèn)值為false

  • trailing,函數(shù)在每個等待時延的結(jié)束被調(diào)用,默認(rèn)值是true

可以根據(jù)不同的值來設(shè)置不同的效果:

  • leading-false,trailing-true:默認(rèn)情況,即在延時結(jié)束后才會調(diào)用函數(shù)

  • leading-true,trailing-true:在延時開始時就調(diào)用,延時結(jié)束后也會調(diào)用

  • leading-true, trailing-false:只在延時開始時調(diào)用

例子:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <input id="input" />
        <script>
            function onInput() {
                console.log('1111')
            }
            const throttleOnInput = throttle(onInput)
            document
                .getElementById('input')
                .addEventListener('input', throttleOnInput) //在Input中輸入,每隔500ms執(zhí)行一次代碼
        </script> 
    </body>
</html>

7. cleanObject

去除對象中value為空(null,undefined,'')的屬性,舉個栗子:

let res=cleanObject({
    name:'',
    pageSize:10,
    page:1
})
console.log("res", res) //輸入{page:1,pageSize:10}   name為空字符串,屬性刪掉

使用場景是:后端列表查詢接口,某個字段前端不傳,后端就不根據(jù)那個字段篩選,例如name不傳的話,就只根據(jù)pagepageSize篩選,但是前端查詢參數(shù)的時候(vue或者react)中,往往會這樣定義

export default{
    data(){
        return {
            query:{
                name:'',
                pageSize:10,
                page:1
            }
        }
    }
}


const [query,setQuery]=useState({name:'',page:1,pageSize:10})

給后端發(fā)送數(shù)據(jù)的時候,要判斷某個屬性是不是空字符串,然后給后端拼參數(shù),這塊邏輯抽離出來就是cleanObject,代碼實(shí)現(xiàn)如下

export const isFalsy = (value) => (value === 0 ? false : !value);

export const isVoid = (value) =>
  value === undefined || value === null || value === "";

export const cleanObject = (object) => {
  // Object.assign({}, object)
  if (!object) {
    return {};
  }
  const result = { ...object };
  Object.keys(result).forEach((key) => {
    const value = result[key];
    if (isVoid(value)) {
      delete result[key];
    }
  });
  return result;
};
let res=cleanObject({
    name:'',
    pageSize:10,
    page:1
})
console.log("res", res) //輸入{page:1,pageSize:10}

8. 獲取文件后綴名

使用場景:上傳文件判斷后綴名

/**
 * 獲取文件后綴名
 * @param {String} filename
 */
 export function getExt(filename) {
    if (typeof filename == 'string') {
        return filename
            .split('.')
            .pop()
            .toLowerCase()
    } else {
        throw new Error('filename must be a string type')
    }
}

使用方式

getExt("1.mp4") //->mp4

9. 復(fù)制內(nèi)容到剪貼板

export function copyToBoard(value) {
    const element = document.createElement('textarea')
    document.body.appendChild(element)
    element.value = value
    element.select()
    if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(element)
        return true
    }
    document.body.removeChild(element)
    return false
}

使用方式:

//如果復(fù)制成功返回true
copyToBoard('lalallala')

原理:

  • 創(chuàng)建一個textare元素并調(diào)用select()方法選中

  • document.execCommand('copy')方法,拷貝當(dāng)前選中內(nèi)容到剪貼板。

10. 休眠多少毫秒

/**
 * 休眠xxxms
 * @param {Number} milliseconds
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

//使用方式
const fetchData=async()=>{
	await sleep(1000)
}

11. 生成隨機(jī)字符串

/**
 * 生成隨機(jī)id
 * @param {*} length
 * @param {*} chars
 */
export function uuid(length, chars) {
    chars =
        chars ||
        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    length = length || 8
    var result = ''
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)]
    return result
}

使用方式

//第一個參數(shù)指定位數(shù),第二個字符串指定字符,都是可選參數(shù),如果都不傳,默認(rèn)生成8位
uuid()

使用場景:用于前端生成隨機(jī)的ID,畢竟現(xiàn)在的Vue和React都需要綁定key

12. 簡單的深拷貝

/**
 *深拷貝
 * @export
 * @param {*} obj
 * @returns
 */
export function deepCopy(obj) {
    if (typeof obj != 'object') {
        return obj
    }
    if (obj == null) {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}

缺陷:只拷貝對象、數(shù)組以及對象數(shù)組,對于大部分場景已經(jīng)足夠

const person={name:'xiaoming',child:{name:'Jack'}}
deepCopy(person) //new person

13. 數(shù)組去重

/**
 * 數(shù)組去重
 * @param {*} arr
 */
export function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
        throw new Error('The first parameter must be an array')
    }
    if (arr.length == 1) {
        return arr
    }
    return [...new Set(arr)]
}

原理是利用Set中不能出現(xiàn)重復(fù)元素的特性

uniqueArray([1,1,1,1,1])//[1]

14. 對象轉(zhuǎn)化為FormData對象

/**
 * 對象轉(zhuǎn)化為formdata
 * @param {Object} object
 */

 export function getFormData(object) {
    const formData = new FormData()
    Object.keys(object).forEach(key => {
        const value = object[key]
        if (Array.isArray(value)) {
            value.forEach((subValue, i) =>
                formData.append(key + `[${i}]`, subValue)
            )
        } else {
            formData.append(key, object[key])
        }
    })
    return formData
}

使用場景:上傳文件時我們要新建一個FormData對象,然后有多少個參數(shù)就append多少次,使用該函數(shù)可以簡化邏輯

使用方式:

let req={
    file:xxx,
    userId:1,
    phone:'15198763636',
    //...
}
fetch(getFormData(req))

15.保留到小數(shù)點(diǎn)以后n位

// 保留小數(shù)點(diǎn)以后幾位,默認(rèn)2位
export function cutNumber(number, no = 2) {
    if (typeof number != 'number') {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}

使用場景:JS的浮點(diǎn)數(shù)超長,有時候頁面顯示時需要保留2位小數(shù)

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI