“This is the 23rd day of my participation in the August Gwen Challenge.

8 essential snippets of JavaScript code for engineering that you can read by listening to blog titles like this. 😀

I am so tired of writing my blog recently. I have been asked to write an article in August. Please don’t give me a “like”, because I don’t want to see the red dot of news notification.

1. Obtain the file name extension

Usage scenario: Determine the file name extension when uploading a file

/** * Obtain the file name 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')}}Copy the code

use

getExt("1.mp4") //->mp4
Copy the code

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
}

Copy the code

Usage:

// Returns true if the copy succeeds
copyToBoard('lalallala')
Copy the code

Principle:

  1. Create a Textare element and call select() to select it
  2. Document. execCommand(‘copy’) method to copy the currently selected content to the clipboard.

3. How many milliseconds to sleep

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

// The usage mode
const fetchData=async() = > {await sleep(1000)}Copy the code

4. Generate random strings

/** * generate 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
}
Copy the code

use

// The first argument specifies the digit and the second string specifies the character. Both are optional arguments. If neither is passed, 8 bits are generated by default
uuid()  
Copy the code

Use scenario: Generate random ids for the front end. After all, Vue and React require binding keys

5. Simple deep copy

/** * deep copy *@export
 * @param {*} obj
 * @returns* /
export function deepCopy(obj) {
    if (typeofobj ! ='object') {
        return obj
    }
    if (obj == null) {
        return obj
    }
    return JSON.parse(JSON.stringify(obj))
}
Copy the code

Drawback: Copying only objects, arrays, and object arrays is sufficient for most scenarios

const person={name:'xiaoming'.child: {name:'Jack'}}
deepCopy(person) //new person
Copy the code

6. Array deduplication

/** * the array is deduplicated@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)]
}
Copy the code

The idea is to take advantage of the fact that no duplicate elements can occur in a Set

uniqueArray([1.1.1.1.1])/ / [1]
Copy the code

7. Objects are converted to FormData objects

/** * object is 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
}
Copy the code

Use scenario: When uploading a file, we need to create a new FormData object and append as many parameters as possible. Using this function can simplify the logic

Usage:

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

8. Keep to n decimal places

// Keep the number of digits after the decimal point, 2 by default
export function cutNumber(number, no = 2) {
    if (typeofnumber ! ='number') {
        number = Number(number)
    }
    return Number(number.toFixed(no))
}
Copy the code

Usage scenario: The floating point number of JS is very long, sometimes the page display needs to reserve 2 decimal places