How many common code blocks do you know about JavaScript?

Time:2020-12-2

preface


This article mainly writes some common JavaScript code blocks. Record common codes for easy reference. If any error is found, please leave a message to correct it.

Read Sanlian: like (), pay attention to (), collect ().

text


1. Convert the URL parameter to an object, and return an empty object if there is no parameter


function formatParamsToObject() {
    let search =  window.location.search , // get the parameter part of the URL
        obj = {};
    if (!search) return obj;
    let params =  search.split (');']
    let paramsArr = params.split('&');
    //Traversal array
    for (let i of paramsArr) {
        let arr = i.split('=');
        Obj [arr [0]] = arr [1] // set the object key and value
    }
    return obj
}

Chestnuts www.baidu.com?id=1&type=2

formatParamsToObject() // {id: "1", type: "2"}

2. Whether the tag tag of the parameter needed to convert the object to URL has a question mark (?)


function formatObjToParamStr(obj, tag = true) {
    let data = [],
        dStr = '';
    for (let key in obj) {
        data.push(`${key}=${obj[key]}`);
    }
    dStr = tag ? '?' + data.join('&') : data.join('&');
    return dStr
}

Chestnuts

formatObjToParamStr({id:1,type:2}) // "?id=1&type=2"
formatObjToParamStr({id:1,type:2},false) // "id=1&type=2"

3. Get the parameter value in the URL through the parameter name


function getUrlParam(name,url) {
    let search = url || window.location.search,
        reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'),
        r = search.substr(search.indexOf('\?') + 1).match(reg);
    return r != null ? r[2] : '';
}

Chestnuts www.baidu.com?id=1&type=2

getUrlParam('id','www.baidu.com?id=1&type=2') // 1

4. Set the cookie and set the max age property to specify the validity period of the cookie (seconds)


function setCookie(name, value, expiretime) {
    let cookie = `${name}=${encodeURIComponent(value)}; path=/`;
    if (typeof expiretime === 'number')cookie += `; max-age=${(60*60*24*expiretime)}`;
    document.cookie = cookie;
}

Chestnuts

setCookie('id',1,1)
document.cookie //"id=1"

5. Read the cookie and get the cookie value corresponding to a single key


function getCookie(name) {
    let cookie = document.cookie;
    let arrCookie = cookie.split('; ');
    for (let i = 0; i < arrCookie.length; i++) {
        let arr = arrCookie[i].split('=');
        if (arr[0] == name) return arr[1];
    }
}

Take a chestnut

getCookie('id') // 1

6. Delete the cookie corresponding to the setting

When Max age is 0, the cookie is deleted


function deleteCookie(name) {
    let currentCookie = getCookie(name);
    if (currentCookie) document.cookie = name + '=' + currentCookie + `; max-age=0}; path=/`;
}

Take a chestnut

deleteCookie('id')
document.cookie // ''

7. Application of anti shake function


If the same function is executed multiple times in a certain period of time, it will be triggered only once

function debounce(fn,delay) {
    let timer = null;
    return function () {
        if(timer) clearTimeout(timer);
        timer = setTimeout(fn,delay)
    }
}

8. Application of throttling function


During a certain period of time, the same function is executed many times, and only the first execution will trigger.

function throttle(fn,delay) {
    let flag = true;
    return function () {
        if(!flag) return false;
        flag = false;
        setTimeout(()=> {
           fn();
           flag = false;
        },delay);
    }
}

Take a chestnut
Scenario: take an input box as an example, monitor the mouse bounce event, output the timestamp within 1s, input multiple times, and execute only once.

let ele = document.getElementsByTagName('input')[0];
ele.addEventListener('keyup',throttle(()=>{
    console.log(Date.now());
},1000));

9. Regular matching mobile phone number


function checkPhone(phone) {
   return /^1[3-9]\d{9}$/.test(phone);
}

Take a chestnut

Checkphone (1890000888) // true this number is written randomly. If you can dial it, you will be informed to modify it

10. Regular matching fixed telephone number


function checkTel (tel) {
   return /^((d{3,4})|d{3,4}-|s)?d{5,14}$/.test(tel)
}

Take a chestnut

Checktel ('12306 ') // true 12306 service hotline
Check Tel ('95105105 ') // true 12306 booking hotline
checkTel('0755-12306') //true

11. Is it an array


function isArray (val) {
   return Object.prototype.toString.call(val) === '[object Array]';
}

Take a chestnut

isArray([]) // true
isArray({}) // false

12. Is it an object


function isObject(val) {
   return Object.prototype.toString.call(val) === '[object Object]';
}

Take a chestnut

isObject([]) // false
isObject({}) // true

13. Is it a numerical value


function isNumber(val) {
   return Object.prototype.toString.call(val) === '[object Number]';
}

Take a chestnut

isNumber(12) // true
isNumber({}) // false

14. Detect whether the object contains an attribute


function checkObjHasAtrr(obj, key) {
   return Object.prototype.hasOwnProperty.call(obj, key);
}

Take a chestnut

checkObjHasAtrr({id: 1, type: 2}, 'id') // true

15. Maximum value of array


function max (arr) {
   if (!isArray(arr) && arr.length) return;
   return Math.max.apply(null,arr);
}

Take a chestnut

max([1,2,3,4,5,6])  // 6

16. Find the minimum value of the array


function min(arr) {
   if (!isArray(arr) && arr.length) return;
   return Math.min.apply(null, arr);
}

Take a chestnut

min([1,2,3,4,5,6])  // 1

17. Generate a new array, which starts from start and has a default value of 0


function toArray (list, start) {
    start = start || 0;
    let i = list.length - start;
    let ret = new Array(i);
    while (i--) {
      ret[i] = list[i + start];
    }
    return ret;
}

Take a chestnut

toArray([1,2,3,4,5,6], 2) // [3, 4, 5, 6]

18. Generate random numbers of random range [min, Max]


explain:
Math.floor : round down
Math.random : generate random numbers 0 ~ 1

function getRandom(min,max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

Take a chestnut

GetRandom (1,2) // 1 randomly generated [1,2]

19. Remove string spaces


Remove leading and trailing spaces

function trim1(str) {
    return str.replace(/(^\s*)|(\s*$)/g, '');
}

Remove all spaces in the string

function trim2(str) {
    return str.replace(/(\s+)/g, ''); 
}

Take a chestnut

trim1(' web api ') // 'web api'
trim2(' web api ') // 'webapi'

20. Prevent default event actions


Preventdefault is used to cancel the default behavior of a target element. Default events, such as the a tab, click Default jump.

function preventDefault(e) {
    e = e || window.event;
    if (e & e.preventDefault) e.preventDefault();
    Else e.returnvalue = false; // IE low version
}

Take a chestnut
Right click to prevent the default event (oncontextmenu) from popping up

document.oncontextmenu  = function (e) {
    preventDefault(e);
}

21. Prevent bubble event operation


Event bubble: if a button is bound to a “click” event, the “click” event will be triggered in its parent element in turn.

function stopPropagation(e) {
    e = e || window.event;
    if (e & e.stopPropagation) e.stopPropagation();
    else e.cancelBubble = true;
}

Take a chestnut
Input, body is Chestnut:

let btn = document.querySelector('input');
let oBody = document.querySelector('body');
btn.onclick = function (e) {
    stopPropagation(e); // 1
    // stopPropagation(e); // 1,2
    console.log(1)
}
oBody.onclick = function () {
    console.log(2);
}

22. Array needed to convert object data


function formatObjToArr(obj) {
    if (!isObject(obj)) return [];
    let options = [];
    for (let i in obj) options.push({
        name: obj[i],
        key: i
    });
    return options;
}

Take a chestnut

formatObjToArr({1: 'Jack', 2: 'Tom'}) // [{name: "Jack", key: "1"},{name: "Tom", key: "2"}

23. Delete an element in the array


function removeArr(arr, val) {
    let index = arr.indexOf(val);
    if (index > -1) arr.splice(index, 1);
    return arr;
}

Take a chestnut

removeArr([1,2,3,4,5,6,7,8],4) //  [1, 2, 3, 5, 6, 7, 8]

24. Array de duplication


function uniqueArr(arr) {
    return Array.from(new Set(arr));
}

Take a chestnut

uniqueArr([1, 2, 1, 3]) //[1, 2, 3]

25. Picture download


Note: it is not supported in the browser provided by wechat. Wechat will intercept it. You can use the js-sdk of wechat. Access control allow origin: access control allow origin:*

function downImage(imageSrc, name) {
    let image = new Image();
    //Dealing with canvas cross domain problem 
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function() {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        canvas.width = image.width;
        canvas.height = image.height;
        context.drawImage(image, 0, 0, image.width, image.height);
        let url =  canvas.toDataURL ('image / PNG '); // image encoding data
        let a = document.createElement('a');
        Let event = new mouseevent ('click '); // create a click event
        a. Download = name |'image '; // set image name
        a. The generated URL is set to a
        a. DispatchEvent (event); // triggers a click event
        a = null,canvas = null;
    }
    image.src = imageSrc;
}

Take a chestnut

downImage('https://bkimg.cdn.bcebos.com/pic/94cad1c8a786c9179e80a80cc23d70cf3bc75700?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2U5Mg==,g_7,xp_5,yp_5')

26. JS deep copy


function deepCopy(obj, cache) {
    if (cache === void 0) cache = [];
    if (obj === null || typeof obj !== 'object') {
        return obj
    }
    let copy = Array.isArray(obj) ? [] : {};
    //Set the cache for the following recursive references
    cache.push({
        original: obj,
        copy: copy
    });
    Object.keys(obj).forEach(function(key) {
        copy[key] = deepCopy(obj[key], cache);
    });
    return copy
}

Take a chestnut

let obj = {
    id: 1,
    name: 'fishStudy520',
    data: [],
    getName: function() {
        return this.name
    }
}
deepCopy(obj); 

27. Get captcha countdown


function getCode(time) {
    let setInter = null,
        codeText = '';
    setInter = setInterval(() => {
        if (time < 1) {
            clearInterval(setInter);
            Codetext: 'get verification code';
        } else {
            Codetext ='sent ${time} s';
            time--;
        }       
    }, 1000);    
}

Take a chestnut

getCode(5)

28. Convert 4-7 bits of mobile phone number into*


function replaceMobile(mobile) {
    return Number.prototype.toString.call(mobile).replace(/1(\d{2})\d{4}(\d{4})/g,'1$1****$2');
}

Take a chestnut

replaceMobile(18000009999) //"180****9999"

29


function request(obj) {
    return new Promise(function(resolve, reject) {
        let { url, method = 'GET', params = {}, isAsync = true } = obj;
        method = method.toUpperCase();
        Let XHR = new xmlhttprequest(); // create an XMLHttpRequest object
        if (method === "POST") {
            xhr.open(method, url, isAsync);
            xhr.setRequestHeader ('content type ','application / JSON'); // JSON data format (take JSON data format as an example)
            xhr.send ( JSON.stringify (params)); // JSON string
        } else {
            let paramsStr = formateObjToParamStr(params);
            xhr.open (method, URL + paramsstr, isasync); // the parameter has been passed in the URL mode
            xhr.send();
        }
        xhr.onreadystatechange = function() {
            if (xhr.status === 200 && xhr.readyState === 4) {
                let response = JSON.parse(xhr.responseText);
                resolve(response)
            } else if (xhr.readyState === 4) {
                reject({
                    code: xhr.status,
                    message: xhr.statusText
                })
            }
        }
    }).catch((e) => console.log(e))
}

Take a chestnut

//Created in current project data.json  file
{
    "code": 200,
    "data": [{
            "id": 1,
            "Name": "JavaScript advanced programming 3rd Edition"
        },
        {
            "id": 2,
            "Name": Javascript authority Guide
        },
        {
            "id": 3,
            "Name": Javascript you don't know
        },
        {
            "id": 4,
            "Name": "JavaScript" you don't know "
        },
        {
            "id": 5,
            "Name": Javascript you don't know
        }
    ]
}

//Function call
(async function getRequestList() {
    let res = await request({
        url: 'data.json',
        method: 'GET',
    });
    console.log(res);
})();

//Direct call
request({ url: 'data.json', method: 'GET',}).then(res=> {
    console.log(res)
})

30. Add 0 before the value


Val: number
Size: length

function addZero(val, size) {
    for (let i = 0, len = size - (val + '').length; i < len; i++) {
        val = '0' + val;
    };
    return val + '';
}

Take a chestnut

addZero(20,5) // "00020"

last


If you like it, please give me a compliment! (╯ε╰)(╯ε╰)(╯ε╰)