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

Implementation of Nginx operation response header information

Prerequisite: You need to compile the ngx_http_he...

JS version of the picture magnifying glass effect

This article shares the specific code of JS to ac...

Implementation of interactive data between QT and javascript

1. Data flows from QT to JS 1. QT calls the JS fu...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

Detailed explanation of sql_mode mode example in MySQL

This article describes the sql_mode mode in MySQL...

How to use javascript to do simple algorithms

Table of contents 1 Question 2 Methods 3 Experime...

HTML tags list and usage instructions

List of HTML tags mark type Name or meaning effec...

MySQL5.7 parallel replication principle and implementation

Anyone who has a little knowledge of data operati...

Docker MQTT installation and use tutorial

Introduction to MQTT MQTT (Message Queuing Teleme...

Introduction to document.activeELement focus element in JavaScript

Table of contents 1. The default focus is on the ...

javascript Blob object to achieve file download

Table of contents illustrate 1. Blob object 2. Fr...

Explanation of the usage scenarios of sql and various nosql databases

SQL is the main trunk. Why do I understand it thi...