JavaScript advanced section 1

Preface: because it is js advanced and writes what I think is important, the content is relatively simple without detailed explanation. It mainly depends on the code.

catalog:

  1. Scope
  2. Floating point number addition, subtraction, multiplication and division
  3. Recursive function
  4. String correlation algorithm
    1. Count the characters with the most occurrences of the string
    2. String de duplication
  5. js determines that the variable is empty
    1. Empty object
    2. Empty array
    3. Empty string
    4. null and undefined

1. Scope

Definition: in JavaScript, the scope is a collection of accessible variables, objects and functions.

Example: the variable a in the first line is a global variable, and the second a is a variable in the show() function. If you print a directly in the immediate execution function, 2 will be output. If the immediate function calls the fn() function, 1 will be output. The reason is to find it in the function first. If it cannot be found, create the scope of the scope (i.e. the function)

var a = 1
function fn(){
    console.log(a);
}
function show(fn){
    var a = 2;
    (function(){
        fn()
    })()
}
show(fn)   //1

2. Floating point number addition, subtraction, multiplication and division

Idea: change decimals to integers       Decimal * multiple, multiple = the square of the longest length after the decimal point of 10

The code is as follows:

The first step is to find the length after the decimal point

function getlength(num) {
    let length = 0;
    try {
    length = String(num).split('.')[1].length
    } catch (e) {
    //TODO handle the exception
    }
    return length;
}

The second step is to find the multiple of multiplication

function getbeishu(numa, numb) {
    let lena = getlength(numa)
    let lenb = getlength(numb)
    let longer = Math.max(lena, lenb);
    return Math.pow(10, longer);
}

The third step is addition, subtraction, multiplication and division

function add(num1, num2) {
    let beishu = getBeishu(num1, num2);
    return (num1 * beishu + num2 * beishu) / beishu;
}

function sub(num1, num2) {
    let beishu = getBeishu(num1, num2);
    return (num1 * beishu - num2 * beishu) / beishu;
}

function mul(num1, num2) {
    let numlena = getlength(num1);
    let numlenb = getlength(num2);
    let num1toStr = String(num1);
    let num2toStr = String(num2);
    return Number(num1toStr.replace('.', '')) * Number(num2toStr.replace('.', '')) / Math.pow(10, numlena + numlenb)
}

function dev(num1, num2) {
    let numlena = getlength(num1);
    let numlenb = getlength(num2);
    let num1toStr = String(num1);
    let num2toStr = String(num2);
    return Number(num1toStr.replace('.', '')) / Number(num2toStr.replace('.', '')) / Math.pow(10, numlena - numlenb)
}

console.log(add(0.01, 0.0002));
console.log(sub(0.01, 0.0002));
console.log(mul(0.01, 0.345));
console.log(dev(0.01, 0.0002));

3. Recursive function

Definition: if a function directly or indirectly calls the function itself, it is called a recursive function. A recursive function must have an ending condition. In short, there is a condition for a function to terminate recursion, a recursive content that needs to be executed all the time, and finally call itself. If there is no termination condition, the function will be called all the time.

Example 1: even sum

function sum(num) {
    if (num % 2 != 0) {
        num--
    }
    if (num == 1) {
        return 1
    } else if (num == 0) {
        return 0
    } else {
        return num + sum(num - 2)
    }
}
console.log(sum(10))

Example 2: Fibonacci sequence

function fn(n) {
    if (n == 0 || n == 1) return 1
    return fn(n - 1) + fn(n - 2)
}
console.log(fn(4)); //1 1 2 3 5 8 13

4. String correlation algorithm

Count the maximum number of characters in the string

Method 1: use object key value pair

function getmax(str) {
    let obj = {}
    for (let i = 0; i < str.length; i++) {
        //If there is no key of this character, it will be added. Take the character as the key and 1-digit value, such as {'h', 1}
        if (!obj[str[i]]) {
            obj[str[i]] = 1
        } else { //If yes, add 1 to the value of the key, such as {'h', 2}
            obj[str[i]]++
        }
    }
    let maxnum = 0
    let maxstr = ''
    //Traverse the object to find the maximum value and the corresponding key
    for (let item in obj) {
        if (obj[item] > maxnum) {
            maxnum = obj[item]
            maxstr = item
        }
    }
    console.log(maxnum);
    console.log(maxstr);
}
let str = 'helloworld'
getmax(str)

Method 2: using str.lastIndexOf() method

let maxnum = 0
let maxstr = ''

function getmax(str) {
    //Convert the string to an array, sort it, and then convert it to a string, such as HelloWorld = > dehlloorw, so that the same characters are together
    let newstr = str.split('').sort().join('')
    for (let i = 0; i < newstr.length; i++) {
        //Position of the last occurrence of the current character - position of the current character + 1 = number of occurrences
        nownum = newstr.lastIndexOf(newstr[i]) - i + 1
        //Find maximum occurrences
        if (nownum > maxnum) {
            maxnum = nownum
            maxstr = newstr[i]
        }
        i = newstr.lastIndexOf(newstr[i])
    }
}
let str = 'helloworld'
getmax(str)
console.log(maxstr);
console.log(maxnum);

String de duplication

Method 1: object key value pair

function deduplication(str) {
    let obj = {}
    let arr = []
    for (let i = 0; i < str.length; i++) {
        if (!obj[str[i]]) { //If the object does not have a key for that character, the key is added and placed in the array
            obj[str[i]] = true
            arr.push(str[i])
        }
    }
    return arr.join('')
}
let str = 'helloworld'
console.log(deduplication(str));

Method 2: use the call() method to call the array filter() method to filter out duplicate characters

function deduplication(str) {
    //Call the filter() method of the array through the call() function
    let newstr = Array.prototype.filter.call(str, function(item, index, arr) {
        //Use the indexOf() function to determine whether it is the first character
        return arr.indexOf(item) === index
    })
    return newstr.join('')
}
let stra = 'helloworld'
console.log(deduplication(stra));

5.js judgment variable is empty

First, empty object

Method 1: Object.keys(obj) can be used in es6

var obj = {};
var arr = Object.keys(obj);
alert(arr.length == 0); //true is empty, false is not empty

Method 2: convert the json object into a json string, and then judge whether the string is "{}"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);   //true is empty, false is not empty

Second, empty array

Method 1:

let arrz = []
if (Array.prototype.isPrototypeOf(arrz) && arrz.length === 0) {
    console.log('true');
}

Method 2:

var item = [];
console.log(JSON.stringify(item) === '[]'); // true

Third, empty string

let str = ''
if (str === '' || str.trim().length == 0) {
    console.log('true');
}

Fourth, null and undefined

if (obj == null) {} // Judge null or undefined
if (obj === undefined) {} //Only undefined can be judged

Keywords: Javascript

Added by shmony on Fri, 03 Dec 2021 15:26:07 +0200