Home > Article > Web Front-end > 15 useful JavaScript code snippets worth collecting (must-have for projects)
This article will share with you 15 JavaScript code snippets that are essential for project engineering. I hope it will be helpful to everyone!
It is also applicable to word, ppt and other documents that browsers do not preview by default, and can also be used after downloading For the stream data returned by the end interface, see 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')
Scenario: I want to download some DOM content. Download a JSON file
/** * 浏览器下载静态文件 * @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) }
Usage:
downloadFile('1.txt','lalalallalalla') downloadFile('1.json',JSON.stringify({name:'hahahha'}))
The data is returned by the backend in the form of an interface, call Use the download method in 1
to 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')
pictures, pdf and other files. The browser will perform preview by default and cannot call the download method. To download, you need to first convert images, pdf and other files into blobs, and then call the download method to download. The conversion method is to use axios to request the corresponding link
//可以用来下载浏览器会默认预览的文件类型,例如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) }) }
Note: There will be restrictions on the same origin policy and need to be configured. Forward
In a certain time interval, if a method is called multiple times, it will only be executed once.
The implementation of this method is copied from the Lodash library
/** * * @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) } } }
Usage:
<!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中输入,多次调用只会在调用结束之后,等待500ms触发一次 </script> </body> </html>
If the third parameter immediate
is passed true, a call will be executed immediately, and subsequent calls will not be executed. You can do it yourself Try it in the code
Call the method multiple times and execute it at a certain time interval
The implementation of this method is also copied from the Lodash library
/** * 节流,多次触发,间隔时间段执行 * @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 }
The third parameter is a bit complicated, options
Different effects can be set according to different values:
Example:
<!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执行一次代码 </script> </body> </html>
Remove the object Attributes whose value is empty (null, undefined, ''), for example:
let res=cleanObject({ name:'', pageSize:10, page:1 }) console.log("res", res) //输入{page:1,pageSize:10} name为空字符串,属性删掉
The usage scenario is: back-end list query interface, if a certain field is not passed to the front-end, the back-end will not filter based on that field. , for example, if name
is not passed, it will only be filtered based on page
and pageSize
, but when querying parameters on the front end (vue or react), it is often defined like this
export default{ data(){ return { query:{ name:'', pageSize:10, page:1 } } } } const [query,setQuery]=useState({name:'',page:1,pageSize:10})
When sending data to the backend, you need to determine whether a certain attribute is an empty string, and then spell the parameters for the backend. This logic is extracted into cleanObject
, code implementation As follows
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}
Usage scenario: upload the file to determine the suffix name
/** * 获取文件后缀名 * @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') } }
Usage method
getExt("1.mp4") //->mp4
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 }
Usage:
//如果复制成功返回true copyToBoard('lalallala')
Principle:
Create a textare element and call the select() method to select
Document.execCommand('copy') method copies the currently selected content to the clipboard.
/** * 休眠xxxms * @param {Number} milliseconds */ export function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } //使用方式 const fetchData=async()=>{ await sleep(1000) }
/** * 生成随机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 }
Usage
//第一个参数指定位数,第二个字符串指定字符,都是可选参数,如果都不传,默认生成8位 uuid()
Usage scenario: use Generate random IDs at the front end. After all, both Vue and React now need to bind keys
/** *深拷贝 * @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)) }
Defects: Only objects, arrays and object arrays are copied. For large Some scenarios are enough
const person={name:'xiaoming',child:{name:'Jack'}} deepCopy(person) //new person
/** * 数组去重 * @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)] }
The principle is to take advantage of the feature that duplicate elements cannot appear in Set
uniqueArray([1,1,1,1,1])//[1]
/** * 对象转化为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 }
Usage scenario: When uploading a file, we need to create a new FormData object, and then append it as many times as there are parameters. Using this function can simplify the logic
Usage method:
let req={ file:xxx, userId:1, phone:'15198763636', //... } fetch(getFormData(req))
// 保留小数点以后几位,默认2位 export function cutNumber(number, no = 2) { if (typeof number != 'number') { number = Number(number) } return Number(number.toFixed(no)) }
Usage scenarios: JS floating point numbers are too long, sometimes 2 decimal places need to be retained when displaying the page
Description: and above The code snippets have been tested by the project and can be used in the project with confidence.
Original address: https://juejin.cn/post/7000919400249294862#heading-3
Author:_Red Scarf
More programming related For knowledge, please visit: programming video! !
The above is the detailed content of 15 useful JavaScript code snippets worth collecting (must-have for projects). For more information, please follow other related articles on the PHP Chinese website!