Maison> interface Web> js tutoriel> le corps du texte

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

青灯夜游
Libérer: 2021-09-10 10:58:57
avant
1511 Les gens l'ont consulté

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

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

1. 下载一个excel文档

同时适用于word,ppt等浏览器不会默认执行预览的文档,也可以用于下载后端接口返回的流数据,见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')
Copier après la connexion

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

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

/** * 浏览器下载静态文件 * @param {String} name 文件名 * @param {String} content 文件内容 */ 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) }
Copier après la connexion

使用方式:

downloadFile('1.txt','lalalallalalla') downloadFile('1.json',JSON.stringify({name:'hahahha'}))
Copier après la connexion

3. 下载后端返回的流

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

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')
Copier après la connexion

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

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

//可以用来下载浏览器会默认预览的文件类型,例如mp4,jpg等 import axios from 'axios' //提供一个link,完成文件下载,link可以是 http://xxx.com/xxx.xls function downloadByLink(link,fileName){ axios.request({ url: link, responseType: 'blob' //关键代码,让axios把响应改成blob }).then(res => { const link=URL.createObjectURL(res.data) download(link, fileName) }) }
Copier après la connexion

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

5 防抖

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

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

/** * * @param {*} func 要进行debouce的函数 * @param {*} wait 等待时间,默认500ms * @param {*} immediate 是否立即执行 */ export function debounce(func, wait=500, immediate=false) { var timeout return function() { var context = this var args = arguments if (timeout) clearTimeout(timeout) if (immediate) { // 如果已经执行过,不再执行 var callNow = !timeout timeout = setTimeout(function() { timeout = null }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function() { func.apply(context, args) }, wait) } } }
Copier après la connexion

使用方式:

      Document 
     
Copier après la connexion

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

6 节流

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

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

/** * 节流,多次触发,间隔时间段执行 * @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 }
Copier après la connexion

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

  • leading,函数在每个等待时延的开始被调用,默认值为false
  • trailing,函数在每个等待时延的结束被调用,默认值是true

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

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

例子:

      Document 
     
Copier après la connexion

7. cleanObject

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

let res=cleanObject({ name:'', pageSize:10, page:1 }) console.log("res", res) //输入{page:1,pageSize:10} name为空字符串,属性删掉
Copier après la connexion

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

export default{ data(){ return { query:{ name:'', pageSize:10, page:1 } } } } const [query,setQuery]=useState({name:'',page:1,pageSize:10})
Copier après la connexion

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

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; };
Copier après la connexion
let res=cleanObject({ name:'', pageSize:10, page:1 }) console.log("res", res) //输入{page:1,pageSize:10}
Copier après la connexion

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') } }
Copier après la connexion

使用方式

getExt("1.mp4") //->mp4
Copier après la connexion

9. 复制内容到剪贴板

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 }
Copier après la connexion

使用方式:

//如果复制成功返回true copyToBoard('lalallala')
Copier après la connexion

原理:

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

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

10. 休眠多少毫秒

/** * 休眠xxxms * @param {Number} milliseconds */ export function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } //使用方式 const fetchData=async()=>{ await sleep(1000) }
Copier après la connexion

11. 生成随机字符串

/** * 生成随机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 }
Copier après la connexion

使用方式

//第一个参数指定位数,第二个字符串指定字符,都是可选参数,如果都不传,默认生成8位 uuid()
Copier après la connexion

使用场景:用于前端生成随机的ID,毕竟现在的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)) }
Copier après la connexion

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

const person={name:'xiaoming',child:{name:'Jack'}} deepCopy(person) //new person
Copier après la connexion

13. 数组去重

/** * 数组去重 * @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)] }
Copier après la connexion

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

uniqueArray([1,1,1,1,1])//[1]
Copier après la connexion

14. 对象转化为FormData对象

/** * 对象转化为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 }
Copier après la connexion

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

使用方式:

let req={ file:xxx, userId:1, phone:'15198763636', //... } fetch(getFormData(req))
Copier après la connexion

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

// 保留小数点以后几位,默认2位 export function cutNumber(number, no = 2) { if (typeof number != 'number') { number = Number(number) } return Number(number.toFixed(no)) }
Copier après la connexion

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

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

原文地址:https://juejin.cn/post/7000919400249294862#heading-3

作者:_红领巾

更多编程相关知识,请访问:编程视频!!

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:掘金--_红领巾
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!