preface

How to create elements and render DOM, re, Math objects,Date objects,Error objects, functions, Object objects, etc. The following is a summary of what I learned this week

An array of

There are two kinds of apis for arrays, one that changes the original array, and the other that does not change the array

Does not change the API of the original array

  1. The method for converting strings is —- join
const arr = [1.2.3.4.5]  
const newArray = arr.join() Const newArray1 = arr.join("") const newArray1 = arr.join("")
const newArray2 = arr.join("-")  
console.log(newArray);  / / 1, 2, 3, 4, 5
console.log(newArray1);  / / 12345
console.log(newArray2);  / / the 1-2-3-4-5
Copy the code
  1. Concatenated array —- concat
const arr = [1.2.3.4.5]  
const newArray = arr.concat([6.7.8])  
console.log(newArray); // [1, 2, 3, 4, 5, 6, 7, 8]
Copy the code
  1. Truncate array —- slice(start, end)

    This method can achieve a deep copy of the array, directly intercept the entire

cosnconst arr = [1.2.3.4.5]  
const newArray = arr.slice(0.2)  
const newArray1 = arr.slice(-3, -1)  
console.log(newArray); // [1, 2
console.log(newArray1); // [3, 4] -- open and close -- negative numbers also work
Copy the code

Change the API of the original array

  1. Delete — add — replace — splice
    // delete arr. Splice (start, delete several)
    const arr = [1.2.3.4.5]
    const newArray = arr.splice(1.2)
    console.log(arr); / / [1, 4, 5]
    console.log(newArray); / / [2, 3]



    // Add arr.splice(start, 0, added) -- delete 0
    const arr = [1.2.3.4.5]
    const newArray = arr.splice(1.0.10.11.12) // add 10,11,12 after the first element
    console.log(arr); // [1, 10, 11, 12, 2, 3, 4, 5]
    console.log(newArray); / / []



    // Replace arr.splice(start, delete, add)
    const arr = [1.2.3.4.5]
    const newArray = arr.splice(1.3.10.11.12) // Delete 3, then add 3,
    console.log(arr); // [1, 10, 11, 12, 5]
    console.log(newArray); / / [2, 3, 4]
Copy the code

Pay attention to

When the splice method involves deleting, it returns a new array of the deleted elements

  1. Reverse the array — reverse
const arr = [1.2.3.4.5]
arr.reverse()
console.log(arr); //[5, 4, 3, 2, 1]
Copy the code
  1. Add push to the end
     const arr = [1.2.3.4.5]
     arr.push(6)
     console.log(arr) //[1, 2, 3, 4, 5, 6]
Copy the code
  1. Delete the end — pop
     const arr = [1.2.3.4.5]
     arr.pop()
     console.log(arr) // [1, 2, 3, 4]
Copy the code
  1. Add — unshift at the beginning
     const arr = [1.2.3.4.5]
     arr.unshift(0)
     console.log(arr) //[0, 1, 2, 3, 4, 5]
Copy the code
  1. Start remove — shift
     const arr = [1.2.3.4.5]
     arr.shift()
     console.log(arr) / / [2, 3, 4, 5]
Copy the code

string

A string is a read-only array of multiple characters (read-only: all strings apis do not modify the original string, only return a new string)

  1. Case conversion – generally used in captchas and other case – insensitive areas
    const str = 'dDSADadsa'
    console.log(str.toUpperCase());  // 'DDSADADSA'
    console.log(str.toLowerCase());  // 'ddsadadsa'
Copy the code
  1. Gets the element with the specified index of the string
    const str = 'dDSADadsa'
    str.charAt(2) // S
Copy the code
  1. Gets the ASCII character at the specified position of the string
    const str = 'adDSADadsa'
    const ascii = str.charCodeAt(0) / / 97
Copy the code

Return to original text by ASCII code

    const str = 'adDSADadsa'
    const ascii = str.charCodeAt(0) / / 97
    const newStr = String.fromCharCode(ascii); // a
Copy the code
  1. Checks if the string exists, returns the corresponding subscript if it does, and -1 if it does not
    // Start with starti and find the first keyword on the right
    const i = str/arr.indexOf('Keyword', starti)

    // starti can be omitted. If omitted, the search starts at position 0
    // Return value: found, returns the subscript of the first keyword
    // if no subscript is found, return -1: we don't care what the subscript is, only if it is -1
    // Check whether there are any
    // The array was added late
Copy the code
    const str = 'abcdefg'
    str.indexOf('b') / / 1
    str.indexOf('s') // -1

    const arr = [1.2.3.4]
    arr.indexOf(1) / / 0
    arr.indexOf(9) // -1
Copy the code

IndexOf can only get the indexOf one keyword. How do I get the indexOf all keywords?

// We can set a variable, change it over and over again, change the variable to the index of the currently found element, and then find all,
    const str = 'abcdcecfg'
    let i = -1
    // Because I starts at 0 and finds the first c, I is assigned 2, not equal to -1, and then prints the first one, and then starts at I + 1
    while ((i = str.indexOf('c', i + 1)) != -1) {
        console.log("Found it:" + i)
    }
Copy the code
  1. Intercept string

    Three methods:

    1. Slice (Starti, endi0) – used in the same way as slice in arrays, but also supports negative numbers
    const str = 'abcde'
    str.slice(1.3) // 'bc' 
    str.slice(-2, -1) // 'd'
    Copy the code
    1. Substring (Starti, endi) — almost the same as above, but it does not support negative numbers

    2. str.substr(starti,n); //n is a number representing the number of intercepts – not counting heads and tails, and negative numbers are also supported

  2. Substitution string

    Str.replace (‘ keyword ‘/ re,’ new content ‘)

    const str = 'abcde'
    str.replace('a'.'f') //'fbcde'
    Copy the code
  3. Split string

    Const arr = str.split(” split “); const arr = str.split(” split “); Special: 1, the cutter does not exist after cutting. 2, the cutter “”, cut every character

    const str = 'a@b@c@d@e'
    const arr = str.split(The '@')
    console.log(arr); // ["a", "b", "c", "d", "e"]
    Copy the code

A lot of times you’re going to have to convert between strings and arrays

Array to string

  1. toString

    This method can be used except for undefined and null

  2. join

    The join() method converts an array to a string, but it can specify a delimiter. When you call the Join () method, you can pass a parameter as a delimiter to join each element. If the argument is omitted, the default comma is used as the delimiter, which is the same as the toString() conversion.

 let a = ['a'.'b'.'g'.'c'.'d'.'e'.'f']
 let b = a.join("-") 
 console.log(typeof(b),b);//string a-b-g-c-d-e-f
Copy the code

String to array

  1. If it is a single string, it can be traversed directly
const a = 'abcdefgh';
const arr = []; 
for(var i = 0; i<a.length; i++){ arr.push(a.charAt(i)); }console.log(arr);//['a', 'b', 'c','d', 'e', 'f','g', 'h']

Copy the code
  1. If it’s a spaced string, split ()

    Split (), which takes two arguments, the first, the separator, and the second, the length of the intercept

    var a = 'a,b,c,d,e,f,g,h' 
    var arr = []; 
    arr = a.split(', '); 
    console.log(arr); // ["a", "b", "c", "d", "e", "f", "g", "h"]
    
    Copy the code

Create the element

It is mainly used to dynamically create elements for the page, such as a list of items, etc., which need to be dynamically rendered

// 1,JS creates an empty element
const elem = document.createElement('Tag name') 

// 2, set the necessary things for this element (the necessary things are different for each tag);Elem. Attribute name = attribute value; Elem. On Event name =function(){}

// 3 render into the DOM tree
father.appendChild(elem)

Copy the code

regular

1. Basic use of regular expressions

Regular expressions are used for cutting, replacing, validating, and so on

  1. The simplest regular expression is ‘no’ –> /no/ig

    I: ignore case and g: all

     const str = 'no sta No sfas no'
     const reg = /no/ig
     const newStr = str.replace(reg, '* * *')
     console.log(newStr); // *** sta *** sfas ***
    Copy the code
  2. Alternate character set: /[Alternate character set]/

    Emphasis: 1, one parenthesis, only one character

    2. Problem 1: By default, the regular expression is satisfied, so we don’t care about the rest, but when we do validation, we expect the user to input all of them

    Solution: as long as it is to do the verification, must: + ^, + $- from beginning to end completely meet our requirements

     const user = 'a'
     const reg = / [0-9]
     reg.test(user) // Return a Boolean value false, a does not meet reg's regular rules, 0-9
    Copy the code

    Question 2: If it is consecutive ASCII characters, we can simply omit the middle part and replace it with a –

    For example, one digit: [0-9] One letter: [A-za-z] One letter, number, underline: [A-za-Z0-9_] One Chinese character: [\ u4e00-U9FA5]

    [^ XXX] -> rarely used, too wide rangeCopy the code
  3. Predefined character set: Simplified alternative character set writing

    A number: \ d a letters, Numbers, underscores, a white space characters: \ w \ s contains Spaces, TAB tabs, newlines an x in addition to change any character:. - > rarely used, the range is too wide Suggestion: formal development, the priority use predefined character set, predefined character set not achieve them with alternative character setCopy the code

    Problem: Each character is only one digit, whether it is an alternate character set or a predefined character

  4. 2. To specify the number of occurrences of a character set:

     1Character set {n,m} : if the character set is adjacent to the front of the character set, the character set must be repeated at least n times and at most m times2, there is no definite number of character sets? : adjacent character set, optional, most1Subset * : indicates the character set adjacent to the preceding character set, which is optional. + indicates the character set adjacent to the preceding character set at least onceCopy the code
  5. Selection and grouping: choice: a commonplace in multiple rules rules 1 | 2 groups: multiple character sets of temporary son a set of rules (rule 1 | rule 2)

    Special: / ^ [0-9] | [a-z] $/ - > to0-9/^([) /^([) /^([) /^([)0-9] | [a-z]) $/ - > from the beginning to the end, either0-9Or is a to zCopy the code
  6. Specify where to match: start: ^ End: $Special: use both, match exactly from start to end – as long as it is for validation!!

  7. Password strength: a combination of four letters and digits, including at least one uppercase letter and one digit /^[0-9a-zA-z]{4}$/ — can only be a combination of four letters or digits

    Prediction formula :(? ! [0-9]+)−> Cannot contain all digits (? ! [A−Z]+) -> Not all digits (? ! [A-z]+)−> Cannot contain all digits. ! [A−Z]+) -> Cannot contain all uppercase letters (? ! [0-9a-z]+$) -> Not all numbers, not all lowercase, and not all combination of numbers and lowercase

 const user = '0000'
 const user1 = 'A000'
 const user2 = '00A0'
 const reg = / ^ (? ! [0-9a-z]+$)(? ! [A-Za-z]+$)[0-9A-Za-z]{4}$/
 // A string of four characters cannot be all lowercase characters, all digits, all lowercase characters and all digits, all uppercase characters and all lowercase characters, all uppercase characters and all lowercase characters, and all lowercase characters and all uppercase characters and all lowercase characters
 console.log(reg.test(user)); // false
 console.log(reg.test(user1)); // true
 console.log(reg.test(user2)); // true
Copy the code

2. Support for regex apis in strings

  1. cutting

     const arr = str.split(str / reg);
    Copy the code
  2. Substitution: – Very common in written tests

    1, basic replacement method:const newStr = str.replace(/reg/g."New content")
    
    2STR = str.replace(/[I fuck you]+/g.function(a,b,c){
    //a Keyword matched by the re
    //b Specifies the subscript of the matched keyword
    / / c is the original
    return a.length==2?"* *":"* * *";
    });
    
    3, formatting:let str = '500235200002066134'
    str=str.replace(/(\d{6})(\d{4})(\d{2})(\d{2})(\d{4})/.function(a,b,c,d,e,f,g,h){
        // In replace, the re is grouped,
        Depending on how many groups you have, there must be two parameters after the parameter a, one for the subscript and one for the original text
        // The contents of the first group are saved in the second parameter
        // The contents of the second grouping are saved in the third parameter
        / /...
        return b+"Year"+c+"Month"+d+"Day";
    })
    Copy the code

3. Regular objects

Create:

Const reg = / regular expression/suffix;

Constructor: const reg = new RegExp(” regular expression “,” suffix “)

Const bool = reg.test(STR); – We get a Boolean value and then we set different styles according to the Boolean value. Different styles determine whether you can submit or not

The Math object

API

  1. integer

    A. Round up: Take an integer (no more than 15 decimal places) whenever you take a little bit more than that.

         const num = 123.456
         const newNum = Math.ceil(num) / / 124
         ​
         // Special: the number of decimal places cannot exceed 15. Once the number is exceeded, this method fails and only rounding is used
         const num = 123.00000000000000000000000123
         const newNum = Math.ceil(num) / / 123
    Copy the code

    B. Round down: No matter how much more, no matter how much more, the decimal part will be omitted

         const num = 123.456
         const newNum = Math.floor(num) / / 123
    Copy the code

    C. Round

    const num = 123.456
    const newNum = Math.round(num) / / 123
    Copy the code

    All three of the above methods can only be rounded. ToFixed can be used instead — it has the ability to round off, and can also be customized to retain decimal places

    Disadvantages: Returns a string

     const num = 123.456
     const newNum = parseFloat(num.toFixed(2)) / / 123.46
    Copy the code
  2. Power and root

    A. Math. Pow (number, power)

    B. Math. SQRT — square only

  3. Max /min(1,2,3,4)

  4. Absolute value — Math. Abs (number)

  5. The random number

    The formula

    Math.random() * (max - min + 1) - min
    Copy the code

The Date object

create

  1. Create current time

     const now = new Date(a)Copy the code
  1. Create a custom time

     const birth = new Date("yyyy/MM/dd hh:mm:ss");
    Copy the code
  2. Create a custom time

     const birth=new Date(yyyy,MM-1,dd,hh,mm,ss);
     // Special: corrects month, starting from 0
    Copy the code
  3. Replication time

     const start = new Date(a)const end = new Date(start) 
    Copy the code
  4. Millisecond creation

     const date = new Date(milliseconds); The computer is saved from1970years1month1day8The number of milliseconds since pointCopy the code

operation

The two dates can be subtracted from each other, giving you a millisecond, which can be used to convert any part of the date you want — the bottom layer of the date is actually a millisecond

The API operations

Unit of time FullYear Month Date Day Week: FullYear Month Date Day Hour minute second millisecond: Hours Minutes Seconds Milliseconds each component has a pair of getXXX/setXXX where getXXX retrieves setXXX Milliseconds. FullYear: current year Number Month: 0-11 Date: 1-31 Day: 0-6 0 indicates Sunday Hours: 0-23 Minutes, Seconds: 0-59 3. If each component of the Date exceeds the value range, the system automatically hexadecimal

    // If you want to add or subtract a component
    ​
    date.setXXX(date.getXXX()+/-n)
Copy the code

Formatting time

    function format(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
    ​
        let hour = date.getHours();
        hour = hour < 10 ? '0' + hour : hour
        let minute = date.getMinutes();
        minute = minute < 10 ? '0' + minute : minute
        let second = date.getSeconds();
        second = second < 10 ? '0' + second : second
    ​
        return `${year}years${month}month${day}Day -${hour}:${minute}:${second}`
    }
    ​
    console.log(format(new Date()));
Copy the code

Error Error object

Browsers come with four types of error objects

  1. SyntaxError: SyntaxError — usually a symbol written wrong somewhere

     while() {// No parentheses
    Copy the code
  2. ReferenceError — used without being created

     console.log(a) // A has not been created yet
    Copy the code
  3. TypeError: TypeError – used for a method or property that is not your own

     const str = 'asdd'
     str.pop() //pop is an array method
    Copy the code
  4. RangeError: RangeError – only encountered in some individual places

     const num = 123.456
     num.toFixed(101) // The number of digits reserved for decimals is between 0 and 100
    Copy the code

    When we encounter an error, we will get an error, which will block subsequent code execution, so we need to do something special

    Using a try… Catch the grammar

 try{error code; }catch(err){execute only if an error is reported; }console.log("Subsequent code")
Copy the code
 const num = 123.456
 
 try{
     num.toFixed(101);
 }catch(err){    
     console.log('You're out of range.');
 }
 console.log("Subsequent code")
Copy the code

Custom throw error

 throw new Error("Custom error text"); // If an error is reported, subsequent code will be blocked
Copy the code

The Function object

  • Functions are really just a way of doing it: mainly for encapsulation, saving code, etc., to achieve “high cohesion, low coupling.”

  • Functions are divided into two parts, creating functions and executing functions

Create a function

  1. A declarative way

    functionThe function name (Parameter,...){function body;returnResults; }Copy the code
  2. Direct quantity mode

    constThe function name =function(Parameter,...){function body;returnResults; }Copy the code
  3. Constructor mode

    When the function body is not fixed, it can be used to concatenate it with strings

    constThe function name =new Function(Parameter "1"."Parameter 2". ."Function body return result");
    Copy the code

The process of creating a function

At creation time, a heap memory space is opened, and the code of the function body is stored in the heap as a string, and the heap address is placed on the execution stack. A variable is then created and associated with the address

Function execution

  1. Program loading

    1. Create JS execution stack (ECS) : An array (stack) that holds the order of function calls
    2. First push the global execution environment (global EC)
    3. Reference global EC to the global object Window
    4. The window holds the addresses of global variables and reference types.
  2. When defining/creating a function

    1. Create a function object: encapsulates the contents of a function’s definition (the function heap points to the address it references)

    2. Define the scope property in the function object, which records the scope from which the function comes. When a function is defined, its scope is already defined, regardless of where it will be executed

       var value = 1;
       ​
       function foo() {
         console.log(value); // 1 -- When the function is created, the scope from which it came is recorded, so it prints global 1, not bar 2
       }
       ​
       function bar() {
         var value = 2;
         foo();
       }
       ​
       bar();
      Copy the code
    3. The scope of a global function is a window

      Foo is defined globally, so its scope is window, get 1

  3. Before the call

    1. Push a new EC into the js stack (function EC)
    2. Create the active object AO: Holds the local variables used in this function call
    3. Add scope chain to function EC referencing AO
    4. Sets the parent property of the AO to the object referenced by the function’s scope
  4. A call

    Rules for using variables: local variables are preferred. If not, they will follow the scope chain up to global

  5. Call out

    The EC of a function is removed from the stack, the AO is released automatically, and local variables are also released automatically

Anonymous functions

It’s a function that doesn’t have a name. Anonymous functions come in two types: callback or callback, either callback or callback

  1. Self-tuning of anonymous functions – can replace global scope

     (function(){
         const a = 10
         console.log(a) / / 10}) ()console.log(a) / / an error
    Copy the code
  2. Anonymous function callback: Pass an anonymous function as an argument to another function call

     arr.sort((a, b) = > a - b)
    Copy the code

    Which functions are callbacks?

    A: Anonymous functions, either auto-callback or callback

     xxx.onclick = function(){} // This is a callback
    Copy the code

The scope chain

Function: Local variables are preferred. If local variables are not available, they will be searched up the scope chain until global

closure

A lexical structure that wishes to protect a local variable that can be used over and over again, combining the advantages of global and local variables

Implementation steps:

  1. Two functions are nested
  2. The outer function creates a protected variable
  3. Execution of the outer function creates and returns the inner function
  4. Inner functions operate on protected variables

Disadvantages: The protected variable is never released because it is always referenced by the inner function. Using closures too much will cause the inner function to leak.

 function foo() {
     let a = 1
     return function() {
         ++a
         return a
     }
 }
 const res = foo()
 ​
 console.log(res()) / / 2
 console.log(res()) / / 3
 console.log(res()) / / 4
 console.log(res()) / / 5
Copy the code

Function: in the development, it can be used to prevent shaking throttling three events: frequent modification of the DOM tree will make the page efficiency lower

  1. Mousemove: Moves the mouse
  2. Input: Input /textarea Input event
  3. Resize: The screen zoom event, which can only be bound to Windows

The formula

 function fdjl(){
     let timer;// Where to save the timer
     return function(){
         // Check whether there is a timer, if there is, empty
         if(timer){clearTimeout(timer)}
         // Start a timer
         timer=setTimeout(function(){
             // Own operations
         },1000)}}varrs=fdjl(); Elem. On Event name =function(){
     rs();
 }
Copy the code