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

Two ways to make IE6 display PNG-24 format images normally

Method 1: Please add the following code after <...

Detailed explanation of the spacing problem between img tags

IMG tag basic analysis In HTML5, the img tag has ...

How to make a website front end elegant and attractive to users

The temperament of a web front-end website is a fe...

SQL ROW_NUMBER() and OVER() method case study

Syntax format: row_number() over(partition by gro...

Detailed steps for installing nodejs environment and path configuration in Linux

There are two ways to install nodejs in linux. On...

A small collection of html Meta tags

<Head>……</head> indicates the file he...

MySQL batch adding and storing method examples

When logging in to the stress test, many differen...

Sample code for cool breathing effect using CSS3+JavaScript

A simple cool effect achieved with CSS3 animation...

v-html rendering component problem

Since I have parsed HTML before, I want to use Vu...