8個(gè)工程必備的JavaScript代碼片段
1. 獲取文件后綴名
使用場(chǎng)景:上傳文件判斷后綴名
/** * 獲取文件后綴名 * @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
2. 復(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)建一個(gè)
textare
元素并調(diào)用select()
方法選中 document.execCommand('copy')
方法,拷貝當(dāng)前選中內(nèi)容到剪貼板。
3. 休眠多少毫秒
/** * 休眠xxxms * @param {Number} milliseconds */ export function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } //使用方式 const fetchData=async()=>{ await sleep(1000) }
4. 生成隨機(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 }
使用方式:
//第一個(gè)參數(shù)指定位數(shù),第二個(gè)字符串指定字符,都是可選參數(shù),如果都不傳,默認(rèn)生成8位 uuid()
使用場(chǎng)景:用于前端生成隨機(jī)的ID,畢竟現(xiàn)在的Vue和React都需要綁定key
5. 簡(jiǎn)單的深拷貝
/** *深拷貝 * @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)) }
缺陷:只拷貝對(duì)象、數(shù)組以及對(duì)象數(shù)組,對(duì)于大部分場(chǎng)景已經(jīng)足夠
const person={name:'xiaoming',child:{name:'Jack'}} deepCopy(person) //new person
6. 數(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]
7. 對(duì)象轉(zhuǎn)化為FormData對(duì)象
/** * 對(duì)象轉(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 }
使用場(chǎng)景:上傳文件時(shí)我們要新建一個(gè)FormData
對(duì)象,然后有多少個(gè)參數(shù)就append
多少次,使用該函數(shù)可以簡(jiǎn)化邏輯
使用方式:
let req={ file:xxx, userId:1, phone:'15198763636', //... } fetch(getFormData(req))
8.保留到小數(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)) }
使用場(chǎng)景:JS
的浮點(diǎn)數(shù)超長(zhǎng),有時(shí)候頁(yè)面顯示時(shí)需要保留2位小數(shù)
結(jié)語:
到此這篇關(guān)于工程必備的JavaScript
代碼片段的文章就介紹到這了,更多相關(guān)工程必備的JavaScript
代碼片段內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
arco?design按需導(dǎo)入報(bào)錯(cuò)排查思路與解決方案解析
這篇文章主要為大家介紹了arco?design?按需導(dǎo)入報(bào)錯(cuò)排查思路與解決方案解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03詳解requestAnimationFrame和setInterval該如何選擇
這篇文章主要為大家介紹了requestAnimationFrame和setInterval該如何選擇示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>2023-03-03微信小程序 動(dòng)態(tài)傳參實(shí)例詳解
這篇文章主要介紹了微信小程序 動(dòng)態(tài)傳參實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04詳解微信小程序開發(fā)之——wx.showToast(OBJECT)的使用
本篇文章主要介紹了微信小程序開發(fā)之——wx.showToast(OBJECT)的使用,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01Performance 內(nèi)存監(jiān)控使用技巧詳解
這篇文章主要為大家介紹了Performance 內(nèi)存監(jiān)控使用技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10JavaScript設(shè)計(jì)模式之命令模式和狀態(tài)模式詳解
這篇文章主要為大家介紹了JavaScript設(shè)計(jì)模式之命令模式和狀態(tài)模式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08