15个值得收藏的实用JavaScript代码片段(项目必备)

 3973

本篇文章给大家分享15个项目工程必备的JavaScript代码片段,希望对大家有所帮助!


15个值得收藏的实用JavaScript代码片段(项目必备)


1. 下载一个excel文档

同时适用于word,ppt等浏览器不会默认执行预览的文档,也可以用于下载后端接口返回的流数据,见3

  1. //下载一个链接 
  2. function download(link, name) {
  3.     if(!name){
  4.             name=link.slice(link.lastIndexOf('/') + 1)
  5.     }
  6.     let eleLink = document.createElement('a')
  7.     eleLink.download = name
  8.     eleLink.style.display = 'none'
  9.     eleLink.href = link
  10.     document.body.appendChild(eleLink)
  11.     eleLink.click()
  12.     document.body.removeChild(eleLink)
  13. }
  14. //下载excel
  15. download('http://111.229.14.189/file/1.xlsx')


2. 在浏览器中自定义下载一些内容

场景:我想下载一些DOM内容,我想下载一个JSON文件

  1. /**
  2.  * 浏览器下载静态文件
  3.  * @param {String} name 文件名
  4.  * @param {String} content 文件内容
  5.  */
  6. function downloadFile(name, content) {
  7.     if (typeof name == 'undefined') {
  8.         throw new Error('The first parameter name is a must')
  9.     }
  10.     if (typeof content == 'undefined') {
  11.         throw new Error('The second parameter content is a must')
  12.     }
  13.     if (!(content instanceof Blob)) {
  14.         content = new Blob([content])
  15.     }
  16.     const link = URL.createObjectURL(content)
  17.     download(link, name)
  18. }
  19. //下载一个链接
  20. function download(link, name) {
  21.     if (!name) {//如果没有提供名字,从给的Link中截取最后一坨
  22.         name =  link.slice(link.lastIndexOf('/') + 1)
  23.     }
  24.     let eleLink = document.createElement('a')
  25.     eleLink.download = name
  26.     eleLink.style.display = 'none'
  27.     eleLink.href = link
  28.     document.body.appendChild(eleLink)
  29.     eleLink.click()
  30.     document.body.removeChild(eleLink)
  31. }

使用方式:

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


3. 下载后端返回的流

数据是后端以接口的形式返回的,调用1中的download方法进行下载

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


4. 提供一个图片链接,点击下载

图片、pdf等文件,浏览器会默认执行预览,不能调用download方法进行下载,需要先把图片、pdf等文件转成blob,再调用download方法进行下载,转换的方式是使用axios请求对应的链接

//可以用来下载浏览器会默认预览的文件类型,例如mp4,jpg等

  1. import axios from 'axios'
  2. //提供一个link,完成文件下载,link可以是  http://xxx.com/xxx.xls
  3. function downloadByLink(link,fileName){
  4.     axios.request({
  5.         url: link,
  6.         responseType: 'blob' //关键代码,让axios把响应改成blob
  7.     }).then(res => {
  8.     const link=URL.createObjectURL(res.data)
  9.         download(link, fileName)
  10.     }) 
  11. }

注意:会有同源策略的限制,需要配置转发


5. 防抖

在一定时间间隔内,多次调用一个方法,只会执行一次.

这个方法的实现是从Lodash库中copy的

  1. /**
  2.  *
  3.  * @param {*} func 要进行debouce的函数
  4.  * @param {*} wait 等待时间,默认500ms
  5.  * @param {*} immediate 是否立即执行
  6.  */
  7. export function debounce(func, wait=500, immediate=false) {
  8.     var timeout
  9.     return function() {
  10.         var context = this
  11.         var args = arguments
  12.  
  13.         if (timeout) clearTimeout(timeout)
  14.         if (immediate) {
  15.             // 如果已经执行过,不再执行
  16.             var callNow = !timeout
  17.             timeout = setTimeout(function() {
  18.                 timeout = null
  19.             }, wait)
  20.             if (callNow) func.apply(context, args)
  21.         } else {
  22.             timeout = setTimeout(function() {
  23.                 func.apply(context, args)
  24.             }, wait)
  25.         }
  26.     }
  27. }

使用方式:

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="UTF-8" />
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7.         <title>Document</title>
  8.     </head>
  9.     <body>
  10.         <input id="input" />
  11.         <script>
  12.             function onInput() {
  13.                 console.log('1111')
  14.             }
  15.             const debounceOnInput = debounce(onInput)
  16.             document
  17.                 .getElementById('input')
  18.                 .addEventListener('input', debounceOnInput) //在Input中输入,多次调用只会在调用结束之后,等待500ms触发一次   
  19.         </script>
  20.     </body>
  21. </html>

如果第三个参数immediate传true,则会立即执行一次调用,后续的调用不会在执行,可以自己在代码中试一下


6. 节流

多次调用方法,按照一定的时间间隔执行

这个方法的实现也是从Lodash库中copy的

  1. /**
  2.  * 节流,多次触发,间隔时间段执行
  3.  * @param {Function} func
  4.  * @param {Int} wait
  5.  * @param {Object} options
  6.  */
  7. export function throttle(func, wait=500, options) {
  8.     //container.onmousemove = throttle(getUserAction, 1000);
  9.     var timeout, context, args
  10.     var previous = 0
  11.     if (!options) options = {leading:false,trailing:true}
  12.  
  13.     var later = function() {
  14.         previous = options.leading === false ? 0 : new Date().getTime()
  15.         timeout = null
  16.         func.apply(context, args)
  17.         if (!timeout) context = args = null
  18.     }
  19.  
  20.     var throttled = function() {
  21.         var now = new Date().getTime()
  22.         if (!previous && options.leading === false) previous = now
  23.         var remaining = wait - (now - previous)
  24.         context = this
  25.         args = arguments
  26.         if (remaining <= 0 || remaining > wait) {
  27.             if (timeout) {
  28.                 clearTimeout(timeout)
  29.                 timeout = null
  30.             }
  31.             previous = now
  32.             func.apply(context, args)
  33.             if (!timeout) context = args = null
  34.         } else if (!timeout && options.trailing !== false) {
  35.             timeout = setTimeout(later, remaining)
  36.         }
  37.     }
  38.     return throttled
  39. }

第三个参数还有点复杂,options

leading,函数在每个等待时延的开始被调用,默认值为false

trailing,函数在每个等待时延的结束被调用,默认值是true

可以根据不同的值来设置不同的效果:

leading-false,trailing-true:默认情况,即在延时结束后才会调用函数

leading-true,trailing-true:在延时开始时就调用,延时结束后也会调用

leading-true, trailing-false:只在延时开始时调用

例子:

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="UTF-8" />
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7.         <title>Document</title>
  8.     </head>
  9.     <body>
  10.         <input id="input" />
  11.         <script>
  12.             function onInput() {
  13.                 console.log('1111')
  14.             }
  15.             const throttleOnInput = throttle(onInput)
  16.             document
  17.                 .getElementById('input')
  18.                 .addEventListener('input', throttleOnInput) //在Input中输入,每隔500ms执行一次代码
  19.         </script> 
  20.     </body>
  21. </html>


7. cleanObject

去除对象中value为空(null,undefined,'')的属性,举个栗子:

  1. let res=cleanObject({
  2.     name:'',
  3.     pageSize:10,
  4.     page:1
  5. })
  6. console.log("res", res) //输入{page:1,pageSize:10}   name为空字符串,属性删掉

使用场景是:后端列表查询接口,某个字段前端不传,后端就不根据那个字段筛选,例如name不传的话,就只根据pagepageSize筛选,但是前端查询参数的时候(vue或者react)中,往往会这样定义

  1. export default{
  2.     data(){
  3.         return {
  4.             query:{
  5.                 name:'',
  6.                 pageSize:10,
  7.                 page:1
  8.             }
  9.         }
  10.     }
  11. } 
  12.  
  13. const [query,setQuery]=useState({name:'',page:1,pageSize:10})

给后端发送数据的时候,要判断某个属性是不是空字符串,然后给后端拼参数,这块逻辑抽离出来就是cleanObject,代码实现如下

  1. export const isFalsy = (value) => (value === 0 ? false : !value);
  2.  
  3. export const isVoid = (value) =>
  4.   value === undefined || value === null || value === "";
  5.  
  6. export const cleanObject = (object) => {
  7.   // Object.assign({}, object)
  8.   if (!object) {
  9.     return {};
  10.   }
  11.   const result = { ...object };
  12.   Object.keys(result).forEach((key) => {
  13.     const value = result[key];
  14.     if (isVoid(value)) {
  15.       delete result[key];
  16.     }
  17.   });
  18.   return result;
  19. };
  1. let res=cleanObject({
  2.     name:'',
  3.     pageSize:10,
  4.     page:1
  5. })
  6. console.log("res", res) //输入{page:1,pageSize:10}


8. 获取文件后缀名

使用场景:上传文件判断后缀名

  1. /**
  2.  * 获取文件后缀名
  3.  * @param {String} filename
  4.  */
  5.  export function getExt(filename) {
  6.     if (typeof filename == 'string') {
  7.         return filename
  8.             .split('.')
  9.             .pop()
  10.             .toLowerCase()
  11.     } else {
  12.         throw new Error('filename must be a string type')
  13.     }
  14. }

使用方式

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


9. 复制内容到剪贴板

  1. export function copyToBoard(value) {
  2.     const element = document.createElement('textarea')
  3.     document.body.appendChild(element)
  4.     element.value = value
  5.     element.select()
  6.     if (document.execCommand('copy')) {
  7.         document.execCommand('copy')
  8.         document.body.removeChild(element)
  9.         return true
  10.     }
  11.     document.body.removeChild(element)
  12.     return false
  13. }

使用方式:

  1. //如果复制成功返回true
  2. copyToBoard('lalallala')

原理:

创建一个textare元素并调用select()方法选中

document.execCommand('copy')方法,拷贝当前选中内容到剪贴板。


10. 休眠多少毫秒

  1. /**
  2.  * 休眠xxxms
  3.  * @param {Number} milliseconds
  4.  */
  5. export function sleep(ms) {
  6.     return new Promise(resolve => setTimeout(resolve, ms))
  7. }
  8.  
  9. //使用方式
  10. const fetchData=async()=>{
  11.     await sleep(1000)
  12. }


11. 生成随机字符串

  1. /**
  2.  * 生成随机id
  3.  * @param {*} length
  4.  * @param {*} chars
  5.  */
  6. export function uuid(length, chars) {
  7.     chars =
  8.         chars ||
  9.         '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  10.     length = length || 8
  11.     var result = ''
  12.     for (var i = length; i > 0; --i)
  13.         result += chars[Math.floor(Math.random() * chars.length)]
  14.     return result
  15. }

使用方式

  1. //第一个参数指定位数,第二个字符串指定字符,都是可选参数,如果都不传,默认生成8位
  2. uuid()

使用场景:用于前端生成随机的ID,毕竟现在的Vue和React都需要绑定key


12. 简单的深拷贝

  1. /**
  2.  *深拷贝
  3.  * @export
  4.  * @param {*} obj
  5.  * @returns
  6.  */
  7. export function deepCopy(obj) {
  8.     if (typeof obj != 'object') {
  9.         return obj
  10.     }
  11.     if (obj == null) {
  12.         return obj
  13.     }
  14.     return JSON.parse(JSON.stringify(obj))
  15. }

缺陷:只拷贝对象、数组以及对象数组,对于大部分场景已经足够

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


13. 数组去重

  1. /**
  2.  * 数组去重
  3.  * @param {*} arr
  4.  */
  5. export function uniqueArray(arr) {
  6.     if (!Array.isArray(arr)) {
  7.         throw new Error('The first parameter must be an array')
  8.     }
  9.     if (arr.length == 1) {
  10.         return arr
  11.     }
  12.     return [...new Set(arr)]
  13. }

原理是利用Set中不能出现重复元素的特性

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


14. 对象转化为FormData对象

  1. /**
  2.  * 对象转化为formdata
  3.  * @param {Object} object
  4.  */ 
  5. export function getFormData(object) {
  6.     const formData = new FormData()
  7.     Object.keys(object).forEach(key => {
  8.         const value = object[key]
  9.         if (Array.isArray(value)) {
  10.             value.forEach((subValue, i) =>
  11.                 formData.append(key + `[${i}]`, subValue)
  12.             )
  13.         } else {
  14.             formData.append(key, object[key])
  15.         }
  16.     })
  17.     return formData
  18. }

使用场景:上传文件时我们要新建一个FormData对象,然后有多少个参数就append多少次,使用该函数可以简化逻辑

使用方式:

  1. let req={
  2.     file:xxx,
  3.     userId:1,
  4.     phone:'15198763636',
  5.     //...
  6. }
  7. fetch(getFormData(req))


15.保留到小数点以后n位

  1. // 保留小数点以后几位,默认2位
  2. export function cutNumber(number, no = 2) {
  3.     if (typeof number != 'number') {
  4.         number = Number(number)
  5.     }
  6.     return Number(number.toFixed(no))
  7. }

使用场景:JS的浮点数超长,有时候页面显示时需要保留2位小数


说明:以上代码片段都经过项目检测,可以放心使用在项目中。

原文地址:https://juejin.cn/post/7000919400249294862#heading-3       作者:_红领巾


TAG标签:
本文网址:https://www.zztuku.com/detail-9169.html
站长图库 - 15个值得收藏的实用JavaScript代码片段(项目必备)
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐