1. Copy text content to clipboard

    function copytoboard(content){
        const element = document.createElement("textarea")
        document.body.append(element)
        element.content = content
        element.select()
        if(document.execCommand("copy")){
            document.execCommand("copy")
            document.body.removeChild(element)
            return true
        }
        document.body.removeChild(element)
        return false
    }
Copy the code

use

// Return 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.

2. Generate random strings

@param {*} chars * @param {*} length */ function uuid(chars, length){ chars = chars || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' length = length || 8 var result = '' for(let i=length; i>0; --i){ result += chars[Math.floor(Math.random()*chars.length)] } return result }Copy the code

use

// Returns true uuid() if replication succeedsCopy the code

3, get the file to determine the suffix name

@param {String} filename */ function getFileSuffix(filename){ if(Object.prototype.toString.call(filename) === '[object String]'){ return filename.split(".")[1].toLowerCase() }else{ throw new Error('filename must be a string type') } }Copy the code

4. Array deduplication

ES6 Set (most commonly used in ES6)

Function unique (arr) {return Array. The from (new Set (arr)]} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; console.log(unique(arr)) //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]Copy the code

Regardless of compatibility, this method of de-duplication has the least code. This method also does not remove the empty ‘{}’ object; later higher-order methods add methods to remove the duplicate ‘{}’ object.

2, use for to nest for, and then splice (ES5 most commonly used)

function unique(arr){ for(var i=0; i<arr.length; i++){ for(var j=i+1; j<arr.length; J ++){if(arr[I]==arr[j]){// if(arr[I]==arr[j]); j--; } } } return arr; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; Console. log(unique(arr)) //[1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", {...}, {...}] //NaN and {} are nullCopy the code

Double loop, outer loop elements, inner loop when comparing values. If the values are the same, delete this value.

3. Use indexOf(includes) to remove weight

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } var array = []; for(var i = 0; i < arr.length; i++) { if (array.indexOf(arr[i]) === -1) { array.push(arr[i]) } } return array; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, NaN, NaN, "NaN," 0, "a", {...}, {... }] //NaN, {} are not deduplicatedCopy the code
function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return } var array =[]; for(var i = 0; i < arr.length; i++) { if(! Array.push (arr[I]); array.push(arr[I]); }} return array} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, NaN, "NaN," 0, "a", {...}, {...}] / / {} not to heavyCopy the code

Create an empty result array, loop through the original array, check whether the result array has the current element, skip if they have the same value, push into the array if they do not.

Sort ()

function unique(arr) { if (! Array.isArray(arr)) { console.log('type error! ') return; } arr = arr.sort() var arrry= [arr[0]]; for (var i = 1; i < arr.length; i++) { if (arr[i] ! == arr[i-1]) { arrry.push(arr[i]); } } return arrry; } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [0, 1, 15, "NaN," NaN, NaN, {...}, {... }, "a", false, null, true, "true", undefined] //NaN, {} is not de-weightedCopy the code

Use sort() sorting method, and then traverse and compare adjacent elements according to the sorted result.

Use hasOwnProperty

function unique(arr) { var obj = {}; return arr.filter(function(item, index, arr){ return obj.hasOwnProperty(typeof item + item) ? false : (obj [typeof item + item] = true)})} var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined. null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}]; Console. log(unique(arr)) //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {...}Copy the code

Use hasOwnProperty to determine whether an object property exists

6. Use filter

Arr. Filter (function(item, index, arr) {return arr. Filter (function(item, index, arr) {return arr. Return arr.indexof (item, 0) === index; }); } var arr = [1, 1, 'true', 'true, true, true, 15, 15, false, false, undefined, undefined, null, null, NaN, NaN,' NaN ', 0, 0, 'a', 'a',{},{}]; The console. The log (unique (arr)) / / [1, "true", true, 15, false, undefined, null, "NaN," 0, "a", {...}, {...}]Copy the code

5. Deep copy

A, JSON. Parse (JSON. Stringify ())

var obj1 = { a: 1, b: 2, c: 3 } var obj2 = JSON.parse(JSON.stringify(obj1)); obj2.a = 5; console.log(obj1.a); // 1 console.log(obj2.a); / / 5Copy the code

Parse (json.stringify ()) cannot copy undefined, function, RegExp, etc

Second, the Object. The assign (target, source)

var obj1 = { a: 1, b: 2, c: 3 } var obj2 = Object.assign({}, obj1); obj2.b = 5; console.log(obj1.b); // 2 console.log(obj2.b); / / 5Copy the code

Object. Assing (target, source) also copies the reference and changes the reference value, which also changes the copy value

Recursive copy

Function deepClone(target) {// define a variable let result; // If (typeof target === 'object') {if (array.isarray (target)) {result = []; // If (array.isarray (target)) {result = []; Result.push (deepClone(target[I]))} // Determine if the current value is null; Else if(target===null) {result =null; } else if(target.constructor===RegExp){result = target; }else {result = {}; for (let i in target) { result[i] = deepClone(target[i]); } else {result = target;} else {result = target; } // return result; }Copy the code

We’ve solved most of the problems with deep copy, but there are a lot of details we haven’t addressed, and we recommend cloneDeep for LoDash.

6, shake and throttle

Debounce

The so-called shaking prevention means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within N seconds, the function execution time will be recalculated.

Anti – shake function is divided into non – immediate execution version and immediate execution version

Non-immediate version:

function debounce(func, wait) { let timeout; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args) }, wait); }}Copy the code

The non-immediate version means that the function is not executed immediately after the event is fired, but n seconds later. If the event is fired within n seconds, the function execution time is recalculated.

Immediate Release:

function debounce(func,wait) { let timeout; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); let callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } }Copy the code

The immediate execution version means that the function is executed immediately after the event is fired, and then the effect of the function cannot be continued until the event is fired for n seconds.

Integrated version:

/** * @desc * @param * @param immediate true * @param immediate true */ function debounce(func,wait,immediate) {let timeout; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = ! timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function(){ func.apply(context, args) }, wait); }}}Copy the code

Throttle

Throttling refers to firing events continuously but executing the function only once in n seconds. Throttling dilutes the execution frequency of the function.

For throttling, there are generally two ways to achieve, respectively, the timestamp version and the timer version.

Timestamp version:

function throttle(func, wait) { let previous = 0; return function() { let now = Date.now(); let context = this; let args = arguments; if (now - previous > wait) { func.apply(context, args); previous = now; }}}Copy the code

Timer version:

function throttle(func, wait) { let timeout; return function() { let context = this; let args = arguments; if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } }Copy the code

Integrated version:

/** * @param func * @param wait * @param type 1 */ function throttle(func, wait,type) {if(type===1){let previous = 0; }else if(type===2){ let timeout; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (! timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } }Copy the code