Home > Web Front-end > JS Tutorial > body text

15 useful JavaScript code snippets worth collecting (must-have for projects)

青灯夜游
Release: 2021-09-10 10:58:57
forward
1608 people have browsed it

This article will share with you 15 JavaScript code snippets that are essential for project engineering. I hope it will be helpful to everyone!

15 useful JavaScript code snippets worth collecting (must-have for projects)

1. Download an excel document

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')
Copy after login

2. Customize downloading of some content in the browser

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)
}
Copy after login

Usage:

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

3. Download the stream returned by the backend

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')
Copy after login

4. Provide a picture link and click to download

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)
    })

}
Copy after login

Note: There will be restrictions on the same origin policy and need to be configured. Forward

5 Anti-shake

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)
        }
    }
}
Copy after login

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(&#39;1111&#39;)
            }
            const debounceOnInput = debounce(onInput)
            document
                .getElementById(&#39;input&#39;)
                .addEventListener(&#39;input&#39;, debounceOnInput) //在Input中输入,多次调用只会在调用结束之后,等待500ms触发一次   
        </script>
    </body>
</html>
Copy after login

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

6 Throttle

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
}
Copy after login

The third parameter is a bit complicated, options

  • leading, the function is called at the beginning of each waiting delay, the default value is false
  • trailing, the function is called at the end of each waiting delay. The default value is true

Different effects can be set according to different values:

  • leading -false, trailing-true: By default, the function will be called after the delay ends
  • leading-true, trailing-true: It will be called at the beginning of the delay and will also be called after the delay ends
  • leading-true, trailing-false: only called at the beginning of the delay

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(&#39;1111&#39;)
            }
            const throttleOnInput = throttle(onInput)
            document
                .getElementById(&#39;input&#39;)
                .addEventListener(&#39;input&#39;, throttleOnInput) //在Input中输入,每隔500ms执行一次代码
        </script> 
    </body>
</html>
Copy after login

7. cleanObject

Remove the object Attributes whose value is empty (null, undefined, ''), for example:

let res=cleanObject({
    name:&#39;&#39;,
    pageSize:10,
    page:1
})
console.log("res", res) //输入{page:1,pageSize:10}   name为空字符串,属性删掉
Copy after login

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:&#39;&#39;,
                pageSize:10,
                page:1
            }
        }
    }
}


const [query,setQuery]=useState({name:&#39;&#39;,page:1,pageSize:10})
Copy after login

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;
};
Copy after login
let res=cleanObject({
    name:&#39;&#39;,
    pageSize:10,
    page:1
})
console.log("res", res) //输入{page:1,pageSize:10}
Copy after login

8. Get the file suffix name

Usage scenario: upload the file to determine the suffix name

/**
 * 获取文件后缀名
 * @param {String} filename
 */
 export function getExt(filename) {
    if (typeof filename == &#39;string&#39;) {
        return filename
            .split(&#39;.&#39;)
            .pop()
            .toLowerCase()
    } else {
        throw new Error(&#39;filename must be a string type&#39;)
    }
}
Copy after login

Usage method

getExt("1.mp4") //->mp4
Copy after login

9. Copy the content to clipboard Board

export function copyToBoard(value) {
    const element = document.createElement(&#39;textarea&#39;)
    document.body.appendChild(element)
    element.value = value
    element.select()
    if (document.execCommand(&#39;copy&#39;)) {
        document.execCommand(&#39;copy&#39;)
        document.body.removeChild(element)
        return true
    }
    document.body.removeChild(element)
    return false
}
Copy after login

Usage:

//如果复制成功返回true
copyToBoard(&#39;lalallala&#39;)
Copy after login

Principle:

  • Create a textare element and call the select() method to select

  • Document.execCommand('copy') method copies the currently selected content to the clipboard.

10. How many milliseconds to sleep

/**
 * 休眠xxxms
 * @param {Number} milliseconds
 */
export function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

//使用方式
const fetchData=async()=>{
	await sleep(1000)
}
Copy after login

11. Generate a random string

/**
 * 生成随机id
 * @param {*} length
 * @param {*} chars
 */
export function uuid(length, chars) {
    chars =
        chars ||
        &#39;0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;
    length = length || 8
    var result = &#39;&#39;
    for (var i = length; i > 0; --i)
        result += chars[Math.floor(Math.random() * chars.length)]
    return result
}
Copy after login

Usage

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

Usage scenario: use Generate random IDs at the front end. After all, both Vue and React now need to bind keys

12. Simple deep copy

/**
 *深拷贝
 * @export
 * @param {*} obj
 * @returns
 */
export function deepCopy(obj) {
    if (typeof obj != &#39;object&#39;) {
        return obj
    }
    if (obj == null) {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}
Copy after login

Defects: Only objects, arrays and object arrays are copied. For large Some scenarios are enough

const person={name:&#39;xiaoming&#39;,child:{name:&#39;Jack&#39;}}
deepCopy(person) //new person
Copy after login

13. Array deduplication

/**
 * 数组去重
 * @param {*} arr
 */
export function uniqueArray(arr) {
    if (!Array.isArray(arr)) {
        throw new Error(&#39;The first parameter must be an array&#39;)
    }
    if (arr.length == 1) {
        return arr
    }
    return [...new Set(arr)]
}
Copy after login

The principle is to take advantage of the feature that duplicate elements cannot appear in Set

uniqueArray([1,1,1,1,1])//[1]
Copy after login

14. Convert objects into FormData objects

/**
 * 对象转化为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
}
Copy after login

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:&#39;15198763636&#39;,
    //...
}
fetch(getFormData(req))
Copy after login

15. Keep to n digits after the decimal point

// 保留小数点以后几位,默认2位
export function cutNumber(number, no = 2) {
    if (typeof number != &#39;number&#39;) {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}
Copy after login

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!

Related labels:
source:掘金--_红领巾
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template