/**
* 数组去重
* @param {*} arr
*/exportfunctionuniqueArray(arr){if(!Array.isArray(arr)){thrownewError('The first parameter must be an array')}if(arr.length ==1){return arr
}return[...newSet(arr)]}
exportfunctioncopyToBoard(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)returntrue}
document.body.removeChild(element)returnfalse}
6. 获取文件后缀名
/**
* 获取文件后缀名
* @param {String} filename
*/exportfunctiongetExt(filename){if(typeof filename =='string'){return filename
.split('.').pop().toLowerCase()}else{thrownewError('filename must be a string type')}}
7. 下载excel
//下载一个链接 functiondownload(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)}//下载exceldownload('http://111.229.14.189/file/1.xlsx')
8. 在浏览器中自定义下载一些内容
/**
* 浏览器下载静态文件
* @param {String} name 文件名
* @param {String} content 文件内容
*/functiondownloadFile(name, content){if(typeof name =='undefined'){thrownewError('The first parameter name is a must')}if(typeof content =='undefined'){thrownewError('The second parameter content is a must')}if(!(content instanceofBlob)){
content =newBlob([content])}const link =URL.createObjectURL(content)download(link, name)}//下载一个链接functiondownload(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)}
exportconstisFalsy=(value)=>(value ===0?false:!value);exportconstisVoid=(value)=>
value ===undefined|| value ===null|| value ==="";exportconstcleanObject=(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;};
JS实用工具函数文章目录JS实用工具函数1.保留到小数点以后n位2.对象转化为FormData对象3. 数组去重4.深拷贝5. 复制到剪贴板6. 获取文件后缀名7. 下载excel8. 在浏览器中自定义下载一些内容9.提供一个图片链接,点击下载10. 防抖11. 节流12. 清除对象中的null.undefined.""1.保留到小数点以后n位// 保留小数点以后几位,默认2位export function cutNumber(number, no = 2) { if (typeof num