8 essential JavaScript code snippets for your project

8 essential JavaScript code snippets for your project

1. Get the file extension

Usage scenario: Upload files to determine the suffix

/**
 * Get the file extension * @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')
    }
}

How to use

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

2. Copy content to clipboard

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
}

Directions:

// Return true if the copy was successful
copyToBoard('lalallala')

principle:

  • Create a textare element and call the select() method to select it.
  • document.execCommand('copy') method copies the currently selected content to the clipboard.

3. How many milliseconds to sleep

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

//Usage const fetchData=async()=>{
 await sleep(1000)
}

4. Generate a random string

/**
 * Generate a random 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
}

Directions:

//The first parameter specifies the number of digits, and the second string specifies the characters. Both are optional parameters. If neither is passed, an 8-bit uuid is generated by default.()  

Usage scenario: used to generate random IDs on the front end. After all, both Vue and React now need to bind keys.

5. Simple deep copy

/**
 *deep copy* @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))
}

Disadvantage: Only copies objects, arrays, and arrays of objects, which is sufficient for most scenarios

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

6. Array deduplication

/**
 * Array deduplication* @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 use the property that no duplicate elements can appear in Set

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

7. Object converted to FormData object

/**
 * Object converted to 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 as many times as there are parameters. Using this function can simplify the logic

Directions:

let req={
    file:xxx,
    userId:1,
    phone:'15198763636',
    //...
}
fetch(getFormData(req))

8. Keep to n decimal places

// How many decimal places to keep, the default is 2 export function cutNumber(number, no = 2) {
    if (typeof number != 'number') {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}

Usage scenario: JS floating point numbers are too long, and sometimes two decimal places need to be retained when the page is displayed

Conclusion:

This is the end of this article about essential JavaScript code snippets for projects. For more content about essential JavaScript code snippets for projects, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Effective Java (Exception Handling)
  • Mono for Android implements efficient navigation (Effective Navigation)
  • Effective C# Use member initializers instead of assignment statements
  • How to determine whether the values ​​of Integer type are equal in Java
  • Specific use of Java third-party library JodaTime
  • Common array operations in JavaScript
  • Summary of the application of Effective Java in work

<<:  Ubuntu starts the SSH service remote login operation

>>:  MySQL 8.0.21 installation tutorial with pictures and text

Recommend

VUE implements token login verification

This article example shares the specific code of ...

Linux common commands chmod to modify file permissions 777 and 754

The following command is often used: chmod 777 文件...

Example code for CSS columns to achieve two-end alignment layout

1. Going around in circles After going around in ...

How to connect to MySQL database using Node-Red

To connect Node-red to the database (mysql), you ...

Implementation steps of encapsulating components based on React

Table of contents Preface How does antd encapsula...

Nginx access control and parameter tuning methods

Nginx global variables There are many global vari...

Detailed explanation of the functions and usage of MySQL common storage engines

This article uses examples to illustrate the func...

MySQL Community Server 5.7.19 Installation Guide (Detailed)

MySQL official website zip file download link htt...

Detailed explanation of the new CSS display:box property

1. display:box; Setting this property on an eleme...

Learn how to write neat and standard HTML tags

Good HTML code is the foundation of a beautiful w...

HTML is the central foundation for the development of WEB standards

HTML-centric front-end development is almost what ...

JavaScript imitates Jingdong carousel effect

This article shares the specific code for JavaScr...