1. Modify the this pointer

// apply modifies this scope
function bindThis(f, oTarget) {
    return function () {
        return f.apply(oTarget,arguments)}}// call modifies this scope
function bindThis(f, oTarget) {
    return function (){
        returnf.call(oTarget,... arguments) } }// bind modifies the this scope
function bindThis(f, oTarget) {
    return function (){
        returnf.bind(oTarget,... arguments)() } }// Or just for short
function bindThis(f, oTarget) {
    return f.bind(oTarget)
}
Copy the code

several

  1. Call and apply return the result of the immediate execution of the function
  2. Bind is not executed immediately
  3. Call receives a list of parameters, and Apply receives an array of parameters

2. Obtain URL parameters

Gets the parameters in the URL

  1. Specifies the parameter name, and returns either the value of the parameter or an empty string
  2. Return all argument objects or {} without specifying argument names
  3. If multiple arguments with the same name exist, an array is returned
  4. The URLSearchParams method is not supported
Input: http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe key Output: [1, 2, 3]Copy the code
function getUrlParam(sUrl, sKey) {
    let res = {};
    let params = sUrl.split('? ') [1].split(The '#') [0].split('&');
    
    params.forEach(ele= > {
        let [key, val] = ele.split('='); //
        if(res[key]){
            res[key] = [...res[key], val];
        }else{ res[key] = val; }})if(sKey === undefined) return res;
    else{
        if(res[sKey] === undefined) return ' '
        else returnres[sKey]; }}Copy the code

ES6:

3. Dom node search

Describes the nearest common parent of two nodes to find, and can include the nodes themselves

Enter description: oNode1 and oNode2 are in the same document and will not be the same node

function commonParentNode(oNode1, oNode2) {
    if(oNode1.contains(oNode2)){
        return oNode1;
    }else{
        returncommonParentNode(oNode1.parentNode, oNode2); }}Copy the code

4. Create objects in the specified space based on the package name

Input description: Namespace ({a: {test: 1, b: 2}}, ‘A.B.C.D ‘)

Output description: {a: {test: 1, b: {c: {d: {}}}}}

function namespace(oNamespace, sPackage) {
    let scope = sPackage.split('. ');
    let ns = oNamespace;
    for(let i = 0; i < scope.length; i ++){
        // If the object does not have the element, or is not an object, then the object is empty
        if(! ns.hasOwnProperty(scope[i]) ||Object.prototype.toString.call(ns[scope[i]]) ! = ='[object Object]'){
            ns[scope[i]] = {};
        }
        // Keep looking
        ns = ns[scope[i]];
    }
    return oNamespace;
}
Copy the code

5. Array deduplication

// Method 1: The ultimate idea
Array.prototype.uniq = function () {
    return [...new Set(this)]}Copy the code
Array.prototype.uniq = function () {
    let arr = [];
    let flag = true;
    this.forEach(value= > {
        if(arr.indexOf(value) === -1) { // Determine the arR new array
            if(value ! == value) {if(flag) {
                    arr.push(value);
                    flag = false; }}else{
                arr.push(value)
            }
        }
    })
    return arr;
}
Copy the code

The main determinant is NaN, indexof(NaN) -1

Fibonacci

// a recursive approach
function fibonacci(n) {
    if(n === 0) return 0
    if(n === 1 || n === 2) return 1
    return fibonacci(n-1) + fibonacci(n-2)}Copy the code

7 Time format output

function formatDate(t, str){
    let year = ' ' + t.getFullYear();
    let month = t.getMonth() + 1;
    let day = t.getDate();
    let hour = t.getHours();
    let minutes = t.getMinutes();
    let second = t.getSeconds();
    let week = ['day'.'一'.'二'.'三'.'four'.'five'.'六'];
    
    let date = {
        'yyyy': year,
        'yy': year.slice(2),
        'MM': ten(month),
        'M': month,
        'dd': ten(day),
        'd': day,
        'HH': ten(hour),
        'H': hour,
        'hh': ten(hour % 12),
        'h': hour % 12.'mm': ten(minutes),
        'm': minutes,
        'ss': ten(second),
        's': second,
        'w': week[t.getDay()]
    }
    
    for(let key in date){
        str = str.replace(key, date[key])
    }
    return str;
}
    
    let ten = num= > num >= 10 ? num : '0' + num

Copy the code

8 Obtain the length of the string

function strLength(s, bUnicode255For1) {
    if(bUnicode255For1) return s.length;
    let len = s.length;
    for(let i = 0; i < s.length; i ++) {
        if(s[i].charCodeAt() > 255) len ++;
    }
    return len;
}
Copy the code

9 Email The character string is matched

function isAvailableEmail(sEmail) {
    return /^[\w\.]+@\w+\.\w+/.test(sEmail)
}
Copy the code

Color string conversion

function rgb2hex(sRGB) {
    let reg = sRGB.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)/)
    if(! reg)return sRGB;
    
    // String concatenation
    let str = The '#';
    for(let i = 1; i < reg.length; i ++) {
       let m = parseInt(reg[i]);
       if(m >=0 || m <= 255){
           str += (m >= 16 ? m.toString(16) : '0' + m.toString(16));
       }else{
           returnsRGB; }}return str;
}
Copy the code