There are a lot of basic knowledge on the net, why write?

  • The Master said, “I am wild when I smell, I forgive when I see, and I am wise when I walk.” The vernacular is: it is heard, easy to forget, see, will vaguely remember, but only after the physical practice, people can truly understand.
  • Give the newbie a basic version of JS that I understand
  • Give the old hands a spot-check version
  • Read, their own practice, JS can be basic entry
  • I have been writing for ten days (5.1-5.10), please point out any omissions!!
  • Help like, comment, bookmark!!
  • This paper covers:

0. Prerequisites:

  • Prerequisites For installing Chrome
  • Install the VScode editor required (you can install others as you like)
  • Installing the NodeJS environment (optional)
  • This article focuses on learning how to use JS rather than understanding the principles

What is javaScript?

Js is a weakly typed scripting language that follows the ECMAScript specification and can run on both the client (browser) and server (nodeJS)

  • Weakly typed: Parameters do not need to be typed explicitly
  • Scripting language: An interpreter is required to interpret the compilation and differentiate chrome V8 engine

What does JS include?

  • BOM: Browser Object ModelProvides the ability to request backend data for JSBOM
  • DOM:Document Object ModelProvides js with the ability to manipulate HTMLDOM
  • ECMAScript(es5 es6 typescript) bomdom.png

What can JS do?

Js can do a lot of things.

  • Client js:
    • Manipulating DOM: Selects the corresponding HTML element. Add, delete, add events to elements (mouse events, keyboard events), and so on
    • Operation BOM: navigation of the page, location API of H5 and so on are obtained from this object
    • Js basics: declare variables, assign values to variables, judge conditions, loop, define functions, execute functions, regular expressions, etc
  • The service side js (nodejs) :
    • Read and write files
    • Build a service that handles requests from the front end and can be returned to the front endHTML JSON image video audioResources such as
    • As a proxy, request other back-end services
    • More on the back of the understanding in depth and then add

Fourth, the first JS program

E6 is the sixth version of the JS syntax, which was released in 2015

  • Client:
    • Type in the browser consoleconsole.log("hello js")Can be
    • Use the editor to create a.js file in it to write JS programs
  • Server (NodeJS environment) : NodeJS has been installed
    • mkdir testCreate a test folder
    • cd testGo to the test folder
    • echo "console.log('hello from nodejs')" > index.jsCreate index.js in the test folderconsole.log('hello from nodejs')
    • Run it in the test directorynode index.jsOutput:hello from nodejs

The nodeJS example is used here to show that JS doesn’t just run in the browser, it’s just known. How to write browser-side JS

How to represent the output

How to express it in js?

  • Document. write writing to HTML is not recommended, and DOM manipulation is required each time
  • Window. alert Browser pop-up box
  • Window.confirm popbox. Window.confirm popbox
  • The window.promot dialog box can be used to enter the content after confirmation. The same as the preceding two boxes, if the following code is displayed, the execution of the following code will be blocked
  • Console.log () outputs to the console. This method is often used to output a value in the browser console called MDN Console

First js program output hello world

  • Above we introduced how to write the first JS program in the browser console, printing simple can, usually we use the editor to write, the following to the actual combat

  • I’m going to create a new folder in vscode whatever it is, I’m going to call it LEARNJAVASCRIPT and I’m going to create ‘index.html’ and I’m going to type it in! Press TAB to quickly generate the basic HTML structure, and write a script tag inside the body. Where this JS code is written, Log (‘ Hello world’) save (CMD + s), open the index.html file in your browser, open the browser console and press Option + Command + J (Mac) or Ctrl + Shift + J (Windows/Linux) should see the effect when opened

  • However, we usually write js code in the new.js file at the end of the file, and then introduce it into the HTML file, and one of the trouble is that every time I modify JS, I want to see the latest effect in the browser, I also need to refresh the browser, so I use the plug-in Live Server to solve the problem, let’s modify the code,LEARNJAVASCRIPTCreating a Directoryindex.jsIn the inputconsole.log(111)Then the index.. Indx.html introduces index.js, which looks like this:

  • Once saved, open it with Live Server. When you open the console in your browser, you should see the following:

  • Live server is a plugin for vscode, it can help us save the code after the browser to see the latest effect, need to install it.

So far we have learned:

  • Edit code using vscode
  • Use the built-in js method console.log() to output values to the console to verify the results of our program
  • Open HTML files using Chrome. Look at the console.log value in js in chrome’s console
  • Use live Server to ensure that the code is updated automatically on the browser side

We then type the new syntax into index.js, save it, and use the Live Server plugin to validate the result in the browser

Seven, comments,

  • What is a comment:

    • Chrome v8 tells the JS interpreter not to execute the commented statement
    • Show developers the necessary comments to facilitate code maintenance
  • How to comment in JS?

    • Single-line comment: use // (CMD + / quick comment again press uncomment). For example // let name = ‘js’

    • Multi-line comments: annotated content with /* * */

      / *let  name = 'jam'
      console.log(name)*/
      Copy the code

Eight, variables,

  • What is a variable

    • It’s a container of values, so values can be numbers, strings, objects, etc., and values can change
  • How to declare: the process of declaring a container

    • Let or const
  • How to assign: The essence of using = is to store a value in the above variable

    • Variable name = variable value
  • How to declare a variable and assign a value?

    • let name = 'js'
  • Variable names (A-zA-Z_ $) : generally easy-to-read English words, following the camel case (multiple words, all lowercase except for the first word, uppercase from the second word), e.g

letLog (first) first = 1 console.log(first) // Declare variables and assign values. The first assignment is called initializationlet name = 'tom'/ / I can giveletThe declared variable is assigned name = again'another name'

let NAME = 'jom'
let className = 'className'
let _test = '_test'
let $this = '$'//Uncaught TypeError: const PI= math. PI //Uncaught TypeError: Assignment to constant variable. // console.log(PI) console.log(name,NAME,className,_test,$this)

Copy the code

The result of executing in the browser is as follows:

Js common data types:

What value variables did you learn, and what values can variables have? Let’s take a look at what data types are available in JS:

  • Numbers : store numbers
  • Strings :pieces of text
  • Booleans : true/false values
  • Undefined: undefined or the initial value is undefined
  • Null: empty
  • Arrays : An array is a single object that contains multiple values enclosed in square brackets and separated by commas
  • Objects :In programming, an object is a structure of code that models a real-life object. You can have a simple object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.
let myNameArray = ['Chris'.'Bob'.'Jim'];
letmyNumberArray = [10, 15, 40]; MyNameArray [0]; // shouldreturn 'Chris'
myNumberArray[2]; // should return 40


Copy the code

When do you use arrays?

  • Emphasize the order of data

When to use objects?

  • When you have a set of properties, like a circle, you have properties like perimeter and area, you can also have a way to calculate the perimeter and area

When do you use a function?

  • Repeat things, put in a function, the parameters of the function to represent the changes, the body of the function to represent the constant (what the function does)

Typeof: checks the typeof data, cannot distinguish complex types (object function null), can distinguish simple types:

Operators

  • Assignment operator:
    • =
    • + =
    • - =
    • * =
    • / =

  • Arithmetic operators:
    • +
    • -
    • *
    • /
    • %
    • 支那

  • Comparison operator: Returns a Boolean value that continues to determine whether it is true or false
    • ‘===’ strictly compares, that is, values are compared as well as types
    • = =Non-strict comparison, only values are compared
    • ! = =
    • >
    • <
    • > =
    • < =

  • Logical operation symbol

    • && and
    • | | or
    • ! non
    • !!!!! Takes a Boolean value for the value
  • Bit-operated symbol

    • &Bitwise and: the corresponding bits are 1 only
    • |Bitwise or: if one of the corresponding bits is 1, it is 1
    • ^If they are the same, 0 is returned. If they are different, 1 is returned
    • ~Bitwise non-x = -(x+1)
    • >>I have a sign and I move it to the right and I fill it with 0’s
    • <<We move left, we move left, we fill out the right with 0’s
    • >>>Unsigned move to the right
    Log (parseInt(2).tostring (2)) // 010 console.log(parseInt(3).tostring (2)) // 011 console.log(parseInt(5).toString(2)) // 101 console.log(parseInt(6).toString(2)) // 101 Console. log(parseInt(7).tostring (2)) // 111 console.log(parseInt(10).tostring (2)) // 1010 // The expression is a piece of code that can calculate the result // 5 101 //  3 011 console.log('5 & 3', 5&3) // 1 by bit with console.log('5 | 3', 5 | 3) / / 111 = > 7 bitwise or console. The log ('5 ^ 3', 5^3) // 110 => 6 If the same returns 0 if the different returns 1 by bit xor console.log('~ 5', ~5) //-6 by bit or console.log('to 3', ~3) // -4
    console.log('5 > > 1', 5>>1) // Unsigned move right 2 console.log(5 < < '1', 5<<1) // Unsigned move left 10 console.log('5 > > > 1', 5>>>1)// 2 The signed right shift of positive numbers is the same as the unsigned right shift console.log('- 1 > > > 1', -1 >>> 1)//2147483647 this is bigCopy the code
  • Triadic operation: Judging conditions? ‘True case’ : ‘false case’ is equivalent to if else

    let score = 60
    let result  = score > 60 ? 'pass':'Fail'The console. The log (result) / / failCopy the code

Xi. Process Control:

  • What is process control?
    • What is the{}Block,let constThe variable defined in{}The variable defined inside can only be used inside the statement, the statement block external access, use the variable, will first look for inside the statement block, can not find to go to the upper statement block, in some cases to find, and then can not find the global role to find, can not find an errorThe variable name is not defined

  • If you go to A, do not go to B
    • if(express || boolean ){}else{}Judge the two cases
    • >2 else if
    • Nested if else
    • switch case

  • Cycle: To do the same thing over and over again
    • The for loop
    • While () {} loop
    • Do {} while loopIt will be executed at least once

  • Infinite loop
// Don't run it! //for 
for(;;) { console.log(1) } //while
while(true){
    console.log(1)
}
Copy the code
  • How do I terminate the loop?break
  • How to get out of the loop?continueThe rest of the cycle continues
for(let i=0; i<10; i++){
  if(i==2) continue
  if(i==5) break
  console.log(i)   
}

let num =0 
whlile(true) {if(num ==1) continue
    
    if(num ==5) break
    console.log(num)
    num++
}

Copy the code

Xii. Functions

  • Functions are particularly important in JS, encapsulating repetitive blocks of code and executing statements with different arguments
  • How do you define a function?
    • function funcNam( arg1, arg2,... argn){ statements }
  • A function that returns no value:
// The function has no return valuefunction log(){console.log(1)} {console.log(1)} Add one parameterfunction log(n){
       console.log(n)
   } 
   
Copy the code
  • A function that returns a value:Statements add return someVariable
// The function returns a valuefunction add(num1, num2){
       return num1 + num2
   }

Copy the code
  • How is the function called (executed)?Function name +()The arguments are the values passed when the function is called, and the parameters are the variables specified when the function is declared
// The function has a return value // the function defines parameter 1 and parameter 2function add(num1, num2){
      returnNum1 + num2} function callletRes = add(1,2) // since the function returns a value, the value after the function call is returned and assigned to the res variable console.log(res) //3Copy the code
  • Return has two functions:

    • Returns some value from the body of the function
    • The next line of return code is not executed
    function getA(a){
        if(a < 0){
            console.log(A should be greater than 0.)
            return 
        }
        return a 
    }
    
    
    Copy the code
  • How is the name of the function printed? Take the example of the add function above: console.log(add.name)// add

  • The default arguments to the function:

// The default argument to the functionfunction l(a = 'defaultvalue'){
       console.log(a)
   }
   l() //defaultvalue
   l(1) //1
Copy the code
  • argumentsKey = index; key = length; key = length; key = length; key = length; key = length
//arguments Computes the sum of any numberfunction sum() {letres = 0; Console. log(arguments) //2 Loop to sum all valuesfor(let i=0; i< arguments.length; i++){
       res += arguments[i]
   }
   return} sum(1,2,3) // class array to arraylet normalArray1 = Array.prototype.slice.call(arguments);
 // -- or --
 let normalArray2 = [].slice.call(arguments);
 // -- or --
 let normalArray3 = Array.from(arguments);
 
Copy the code

  • The remaining parameters.
   functionsumWithArgs(... theArgs){ // console.log(theArgs)let res = 0;
       for(let i=0; i< theArgs.length; i++){
           res += theArgs[i]
       }
       returnRes} console.log(sumWithArgs(1,2,3,4,5)) //15 console.log(sumWithArgs(1,2,3)) //6 overwrite with array reducefunctionsumWithArgsAndReduce(... theArgs){returntheArgs.reduce( (acc ,next) => acc += next , 0)} the console. The log (sumWithArgsAndReduce (1, 2, 3, 4, 5)) console. The log (sumWithArgsAndReduce (1, 2, 3))Copy the code

  • Scope: The effective range of a variable
    • Local scope: a variable defined inside a function that can only be used inside the function. A local scope can access variables in a global scope
    • Global scope: external to a function

  • How to write a function well? Clean Code Book Review adopts a top-down approach, first realizing the big box (trunk), and then filling in details for each function to make the code clear and expressive
  • What is the form of the function?
    • The function keyword declares functions:
    • Arrow function: Short for es6 function
    • Function expression: A function is assigned to a variable
    • IEFE: Immediately Invoked Function Expression
    • Callback: function as argument

var num1 = 10 ; (function(){// Self-executing functions have their own function scope, Avoid conflicts with global variables of the same name var num1 = 1 console.log(num1)//1})() console.log(num1)//10 //IEFE Immediately Invoked Function Expressionlet IEFE = (function(){
    console.log(1)
})()
let IEFE1 = +(function(){
    console.log(1)
})()
let IEFE2 = -(function(){
    console.log(1)
})()
let IEFE3 = ~(function(){
    console.log(1)
})()
Copy the code

  • Functions are first-class functions in JS
    • Functions are objects
    • A function can be assigned to a variable
    • A function can be passed as an argument to another function
    • A function can be the return value of another function
    • HOC (higher-order functions
      • What is a higher-order function? A function that takes an argument or returns a value from another function is a higher-order functionFunctions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions

      HOC is in favor of abstract repetition (loops) in favor of functional programming FP (a programming paradigm, pure function, stateless), procedural programming (what should be done at each step, solve all the steps, and the problem is solved), and object-oriented programming OOP: Object Oriented Programming OOP focuses on the packaging of data and behavior and the decoupling of the program interface and implementation, the process of solving the problem is the process of calling the Object related methods), and AOP Oriented Programming, a horizontal aspect, each class should perform this step, Take that step out of the way, do it all together, add the classes you need how to trigger, when to trigger, etc., what programming paradigm should you use in your work? What paradigm is needed when to use what paradigm, need to accumulate to experience

      • How does HOC abstract repetition?
      • Let’s first look at how to do this without HOC[1, 2, 3]become,3,6 [2]?
      letRes = [1, 2, 3]let result = []
      for(let i = 0; i< res.length; i++){
          result.push(res[i] * 2)   
      }
      Copy the code
      • How do you do that with HOC?
      let result = res.map( x => x * 2 )
      Copy the code
      • Array.prototype.map is HOC because the argument is a function. Array.prototype Is an object that stores methods used by Array instances. [] || new Array(2)

      • Implement an array map function?

      // To implement a simple map with no initial checksum, this is handled as // 1 returns a value so we declare an array // 2 because it is a higher-order function, so we have a callback cb // 3 because it is multiple, so we loop. // 4 Returns array.prototype. _map =. // 4 returns array.prototype. _map =function(cb){// array. prototype this is an Array instance that can use the prototype methodlet result = []
          for(let i=0; i < this.length; i++){
              result.push( cb(this[i], i, this))
          }
          returnResult} res2 = res._map(x => x*2) //[2,4,6]Copy the code

  • What is a closure?Closures preserve the outer scope inside an inner scope

What is the difference between first-class functions and HOC and closure?

- `first-class functions`: The function can be assigned as an argument to a variable - 'HOC' : the argument of the function or the return value can be a function - 'closure' : Closures preserve the outer scope inside an inner scopeCopy the code

13. Arrays

  • What an array is: Stores one or more data structures of the same type or different types sequentially, usually of the same type.

  • How is an array created?

    • Literal way:
    • Constructor:
    • New Array: Declares a specified number of empty elements
    • Array.of: Setting one parameter does not create empty elements. Setting multiple parameters creates multiple empty elements
    • Array.from: You can also convert an Array of classes to an Array
    • […arrayLike]
    // Create an array //1 literal is often usedletArr = [1, 2, 3]. The console log (arr) / / [1, 2, 3] / / / / 2 constructorletArr2 = Array(3) console.log(arr2)//[empty × 3] // //3 new Array(3)letArr3 = new Array(3) console.log(arr3) //[empty × 3] // //4 array.of (3) Create oneletarr4 = Array.of(3) , Arr4Multi = array. of(3,4,5) console.log(arr4) //[3] console.log(arr4Multi)// [3,4,5] // //5 array. from({length:3}, (v, I)=> I) Quickly create multiple arrays to useletArr5 = Array. The from ({3} length:, (v, I) = > I). The console log (arr5) / / [0]let str ='alex'
    console.log(Array.from(str))// ['a'.'l'.'e'.'x']
    
    let arr3Hello = Array.from({length:3}, (v,i)=> 'hello')
    console.log(arr3Hello)//["hello"."hello"."hello"]
    
    let divs = document.querySelectorAll("div");
    [...divs].map
    
    
    
    Copy the code
  • Let arr = [‘item1′,’item2’]

  • Array data access:

    • Array length: arr.length
    • Array subscripts start at zero and end at arr. Length-1
    • Deposit:
      • arr[index] =val
    • Pick up:
      • arr[index]0<=index <= arr.length-1

  • Methods on array constructors: constructorArrayuse
    • Array.from
    • Array.isArray()
    • Array.of()
    // Console. log(array.isarray (arr)) //false
    console.log(Array.isArray("foobar")) / /falseconsole.log(Array.of(7)) // [7] console.log(Array.of(1, 2, 3) )// [1, 2, 3] console.log(array. from({length:3}, (v, I) = > I)) / / [0] / / Array. The from (document. GetElementsByName ('div')) 
    
    
    
    Copy the code
  • Methods on array prototypes: Instances can be used directly.
  • Remove elements
letArr = [1,2,3,4,5,6] // Delete the last item arr.length = arr.length-1 console.log(arr)//[1, 2,3,4, 4,5,6] 5] // Drop the element with the specified subscript, for example, the element with the subscript 2 is 3. Log (arr) //[1,2,4,5] / / https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/splice / / starting from the second delete zero elements, Insert the "drum"let  myFish = ["angel"."clown"."mandarin"."sturgeon"];
myFish.splice(2, 0, "drum");
console.log(myFish)// ["angel"."clown"."drum"."mandarin"."sturgeon"]


Copy the code
  • Array traversal
    • The for loopPrints each item of the array and its corresponding subscript
    • for ofOutput array each item iterates over the iterable, and arrays are iterable objects
    • forEachPrints each entry of the array, subscript, and the array itself
    // Array traversallet myFish1 = ['hello'.'array'];
    
    //forcyclefor(let i=0,len=myFish1.length; i<len; i++){
        console.log(myFish1[i])
    }
    //forOf circulationfor(let i of myFish1){
        console.log(i)
    }
    //[].forEach((ele, index, arrSelf)=> {})
    ['hello'.'array'].forEach((ele, i, myFish)=>{
        console.log(ele,i ,myFish)
    })
    
     let names1 = ['alex'.'tom']
    const iterator = names1.entries()
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator)
    for(let [key,value] of names1.entries()){
        console.log(key,value)
    }
    
    Copy the code

  • Stack and queue modes for arrays
// The stack is a Last In First Out (LIFO) data structure. All entries and exits are operated at the top of the stack, and those far from the top are called the bottom of the stackletStack = [] / / into the stack stack. Push (1) / / | 3 | stack. Push (2, 3) / / 2 | | the console. The log (stack) / / [1, 2, 3] / / | 1 | / / out of the stack The console. The log (stack. Pop ()) / / 3 removed from the stack / / 2 | | / / | 1 | console. The log (stack. Pop ()) / / 2 from the top to remove the console. The log (stack) / / [1] Console.log (stack.pop()) //undefined console.log(stack.pop()) // Array_queue (array_queue) You can also remove elements from the headerletQueue = [] queue.push(1,2,3) console.log(queue) // remove an element from the headerletFirstRemoved = queue.shift() console.log(firstRemoved) console.log(queue) // Add an element from the header queue.unshift('first')
console.log(queue)
Copy the code
  • Array lookup element

    • indexOfIf the element is not found, return -1. The second argument can specify the position to be searched
    • lastindexOf
    • includesTo find if a string return value is a Boolean, look only for the primitive type
    • findYou can look for base and reference types
    • findIndexReturns the index value, -1 if not found
    //index of basic types in the array const beasts = ['ant'.'bison'.'camel'.'duck'.'bison'];
    console.log(beasts.indexOf('bison')); //1 console.log(beasts.indexOf('giraffe')// -1 //lastindexOf index const animals = ['Dodo'.'Tiger'.'Penguin'.'Dodo'];
    console.log(animals.lastIndexOf('Dodo'))//3
    console.log(animals.lastIndexOf('Tiger'Const array1 = [5, 12, 8, 130, 44]; //1 // //find array1 = [5, 12, 8, 130, 44]; Const found = array1.find(element => element > 10) const found = array1.find(element => element > 10)'apples', quantity: 2},
        {name: 'bananas', quantity: 0},
        {name: 'cherries', quantity: 5}
    ];
    console.log(inventory.find(fruit.name === 'cherries')); // { name: 'cherries'// // array11 = [5, 12, 8, 130, 44]; // // array11 = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; console.log(array11.findIndex(isLargeNumber) , array1); //3 Array [5, 12, 8, 130, 44]Copy the code
  • Sort an array

    • reverse: Reverse array
    • sort: Sort the array from smallest to largest by default when comparing two values at a time. You can also define your own sorting rules
    // Invert the arraylet testArr = [1, 2, 3] the console. The log (testArr.reverse()) //[3, 2, 1] // Non-arrays are converted to arrays before reveselet helloStr = 'hello'
    let rervesedStr = helloStr
                        .split(' '// The string method cuts the empty string into an array.reverse ()// The previous step became an array, so you can use the array method to reverse the array.join ()' ')// Array methods are concatenated with Spaces to convert the array to console.log(rervesedStr) // ollehletSortArr1 = [1,3,7,5] console.log(sortarr1.sort (),sortArr1)//[1,3,5,7] console.log(sortarr1.sort ((a,b)=> A - b)) / / hc-positie [1] ascending will change the original array. The console log (sortArr1. Sort ((a, b) = > b-a) // the descending order of [7,5,3,1] changes the original arrayCopy the code
    • ToLocaleString, flat: flat array
            //toLocaleString
    const array111 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
    const localeString = array111.toLocaleString('en', { timeZone: 'UTC'}); console.log(localeString); Var arr1 = [1, 2, [3, 4]]; var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); / / [1, 2, 3, 4, 5, 6] / / use the Infinity, expandable any depth of nested array var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]. arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Copy the code
    • some every
    Const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold), array1); //true, [1, 30, 39, 29, 10, 13] does not change the original arraytrueConst array = [1, 2, 3, 4, 5]; // checks whether an element is even const even = (element) => element % 2 === 0; console.log(array.some(even), array) //true[1, 2, 3, 4, 5] does not change the original arrayCopy the code
    • map filter reduce
        //filter
    const words = ['spray'.'destruction'.'present']; const result = words.filter(word => word.length > 6); console.log(result ,words); //map const arr = [1,2,3] const arr2 = arr.map(x=>x*2) console.log(arr, arr2)//[1, 2,3] [2, 4, Reduce console.log(arr.reduce((acc,next)=> acc += Next)) // Sum 6 console.log(arr.reduce((acc) ,next)=> acc += next, 100)) // Specify the initial sum of 100+ 6 = 106Copy the code
    • Array crop:slice
    // Slice slice returns the new array unchanged from the original arrayletArr12345 = [1,2,3,4,5] console.log(arr12345.slice(), ARR12345)//[1, 2,3,4,5] (5) [1,2,3,4, 4, 5] console.log(arr12345. Slice (0))//[1, 2, 3, 4, 5] Copy array // include front but not back console.log(arr12345. Slice (1))//[2, 3, 4, Log (arr12345. Slice (1,-1)) // [2, 3, 4]Copy the code
    • Array deconstruction
    // Array destructletNumbers = [3, 4, 1} {name:]let[a, b,c] = numbers console.log(a,b,c) // Console. log(a,b,clet[a1,...args] = numbers console.log(a1, argslet [,, {name}] = numbers
    console.log(name) //1 
    Copy the code

    • 2 d array
    // A two-dimensional arraylet arr = [ ['alex'], ['age']]
    console.log(arr[0][0])// alex
    Copy the code

Xiv. Objects

Commonly used to represent a collection of properties or methods, no order required

  • How is an object created?

    • Literal way:let person = {name:1,age:2 }
    • new Object():
    let person = new Object()
    person.name = 'alex'Person. Age = 18 //console.dir Console output object console.dir(person)Copy the code
  • Object syntax: Only key and value correspond. The direct order of keys and keys is not guaranteed

/ / syntax:letObj = {key1: value1, key2: value2}let person = {
     name : 'alex',
     age : 18
     sayName : ()=> conole.log(this.name)
 }
 
 
Copy the code
  • Access to object properties
    • Assignment:Key = value or obj['newKeyName'] = value
    • Values:Let {name,age} = {name:1,age:2}

  • Omit the key

    //
     let name = 'alex'
     let person = {
         name : name,
         sayName: function(){console.log(1)}} // Same key value or shortfunction
     let person={
         name,
         sayName(){
             console.log(1)
         }
     }
    
    
    Copy the code
  • “use strict”; Strict mode

    • How to turn it on: To turn on strict mode for the entire script file, place a specific statement “use strict” before all statements; (or ‘use strict’;)
    • What’s the use? MDN use strict
  • Delete key: delete: The object can be deleted only when it can be deleted

    let person={
        name,
        sayName(){console.log(1)}} // object.keys return array console.log(object.keys (person))//["name"."sayName"]
    delete person.name
    console.log(Object.keys(person))//["sayName"] // Signals can be deleted without any additional information. Object.defineProperty(o,'a', {
      get() { return 1; },
      configurable: false}); console.log(o.a); //1 delete o.console. Log (o.a) //1 is still 1Copy the code
  • The Object.defineProperty method directly defines a new property on an Object, or modifies an existing property of an Object, and returns the Object. This approach allows a precise attributes of the object to add or modify, vue2.0 a front-end framework, encapsulate some commonly used function, accelerate development, use it to follow the rules for its use of the API to realize two-way binding (data modification will automatically update the binding of the dom, update interface, without manual operation the dom, dom will set the change data binding)

    Writable property: When the Writable property is set to false, this property is said to be “Writable”. It cannot be reassigned.

    Enumerable: Enumerable defines whether an object’s property can be considered in a for… Are enumerated in the in loop and object.keys (). The property of a different object indicates whether the property of the object can be deleted, and whether any other features other than value and writable can be modified. Custom Setters and Getters

        function Archiver() {
        var temperature = null;
        var archive = [];
      
        Object.defineProperty(this, 'temperature', {
          get: function() {
            console.log('get! ');
            return temperature;
          },
          set: function(value) { temperature = value; archive.push({ val: temperature }); }}); this.getArchive =function() { return archive; };
      }
      
      var arc = new Archiver();
      arc.temperature; // 'get! '
      arc.temperature = 11;
      arc.temperature = 13;
      arc.getArchive(); // [{ val: 11 }, { val: 13 }]
    Copy the code
  • HasOwnProperty Determines whether an object itself contains an attribute

    // Determine whether the object itself contains an attributelet p= {}
    console.log(p.hasOwnProperty('time')) / /false
    p.name = 'alex'
    console.log(p.hasOwnProperty('name')) / /true
    
    Copy the code
  • Common methods for objects

    • Merge two objects:
        let config = {name:1,age:2}
        let newConfig = {name:2, time:'2020 -' 05 - '}
        letfinalObj = {... config, ... NewConfig} console.log(finalObj) // Update only one property of the object such as the name property finalObj = {... finalObj, name:'testName'}
    Copy the code
    • Traverse object
    let p = {
        name :'alex',
        age : 18,
        sayname(){
            console.log('1')}}let keys = Object.keys(p)
    let values= Object.values(p)
    console.log(keys,values)//(3) 
    //["name"."age"."sayname"[] (3)"alex", 18, ƒ] / /for in 
    for(let key in p ){
        console.log(key, p[key])
    }
    Copy the code
    • This: The environment object currently executing the code, in non-strict mode, always refers to an object, in strict mode can be any value, the following discussion is client side this, not including nodeJS side JS

    • Scopes include: global scope Function scope Eval scope module scope

    • This in global scope refers to the global object Window: in the global execution environment (outside any function body) this refers to the global object, whether in strict mode or not.

      // In browsers, the window object is also a global object: console.log(this === window); //true
       console.log(this === top); // trueconsole.log(window === top); //true// Undeclared variables become window attributes a = 37; console.log(window.a); // 37 this.b ="MDN";
       console.log(window.b)  // "MDN"
       console.log(b)         // "MDN"
      
      Copy the code
    • Function scope this refers to the decision when the function is called. Whoever is in front is who

    • The window.settimeout () and window.setinterval () functions are a bit special in that this is the window object by default.

    • In constructors and stereotypes, this refers to the corresponding instance

    • Arrow function this: The arrow function is not bound to this; its this depends on the value of this of the non-arrow function outside the function

    • As methods of objects, their this is the object on which the function is called

    • This in getters and setters: Functions that serve as getters or setters bind this to the object that sets or gets the property.

        function sum() {
      return this.a + this.b + this.c;
    }
    
    var o = {
      a: 1,
      b: 2,
      c: 3,
      get average() {
        return(this.a + this.b + this.c) / 3; }}; Object.defineProperty(o,'sum', {
        get: sum, enumerable: true, configurable: true});
    
    console.log(o.average, o.sum); // logs 2, 6
    
    Copy the code
    • When a function is used as an event handler, its this refers to the element that triggered the event. (Some browsers do not follow this convention when dynamically adding listeners using functions that are not addeventListeners.)
    // When called, turn the associated element bluefunctionbluify(e){ console.log(this === e.currentTarget); / / alwaystrueCurrentTarget when the currentTarget and target are the same objecttrue
      console.log(this === e.target);        
      this.style.backgroundColor = '#A5D9F3'; } / / get the document list of all the elements in the var elements = document. The getElementsByTagName (The '*'); // Use Bluify as the click-listening function for the element, which turns blue when the element is clickedfor(var i=0 ; i<elements.length ; i++){
      elements[i].addEventListener('click', bluify, false);
    }
    
    Copy the code
    • As an inline event handler, this points to the DOM element where the listener resides
    // This is button <button onclick="alert(this.tagName.toLowerCase());"> Show this </button> // window So it points to the global/window object (that is, the default object to which non-strict call-back functions point if this is not set) <button onclick="alert((function(){return this})());">
      Show inner this
    </button>
    Copy the code
  • How do I change this?

    • callThe first argument to be changed is this followed by multiple arguments that are immediately executed
    
    function greet() {
      var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' ');
      console.log(reply);
    }
    
    let  obj = {
      animal: 'cats', sleepDuration: '12 and 16 hours'
    };
    
    greet.call(obj);  // cats typically sleep between 12 and 16 hours
    
    Copy the code
    • The first argument to apply is to change this immediately followed by the array form

    • Bind changes this before it can be called again

    • Let’s start with a wave of this pointing to the problem

        let person = {
    name :'alex',
    sayName :function() {the console. The log (` name is${this.name}`)},say(){ console.log(`arrow say ${this.name}`)},
    group:{
        name :'groupName'.logName(){
            console.log(`group name is ${this.name}`)}}}function windowSayName(){
        console.log(`windonw say name is : ${this.name}')} console.log(person.sayname ())// name is Alex console.log(person.say())//arrow say Alex Console.log (person.group.logName()) //group name is groupName // No output because window has no name console.log(windowSayName())//windonw say name is :Copy the code
    • usecall apply bind
    //call apply bindModify this to point tolet person = {
        name :'alex',}function windowSayName(age,group){
        console.log(`windonw say name is : ${this.name},age:${age},group:${group}`)
    }
    console.log(windowSayName.call(person , 18,'fe' ))
    //windonw say name is : alex,age:18,group:fe
    
    console.log(windowSayName.apply(person, [18, 'fe']))
    //windonw say name is : alex,age:18,group:fe 
    
    console.log( typeof windowSayName.bind(person, [18, 'fe')) / /function
    console.log( typeof windowSayName.bind(person, [18, 'fe'])() )
    //windonw say name is : alex,age:18,fe,group:undefined
    
    Copy the code

  • Constructor: analog reality: a human is a constructor and a specific person is an instance. In JS, constructor names are usually capitalized, and instances are generated through new calls

    
    // function Person(name,age){
    //     this.name = name
    //     this.age = age
    // }
    // let p1 = new Person('alex'18),Copy the code
    • The difference between a constructor and a normal function:

      • thisInside the constructor this points to the newly created object instance, the normal function this. In strict mode, this means undefined. In non-strict mode, this refers to window.
      • newConstructor calls require new, normal functions do not
      • return: A normal function returns a value after a return, but returns undefined if there is no value or if there is no return. Constructors generally do not need to use a return. If you return a primitive type value, you can ignore the return statement. If the return value is a reference type, the reference type itself is returned.
    • Example constructor prototype relationship, two diagrams are done:

What is a prototype chain

  • Get the prototype of the Object: Object.getProtoTypeof

  • Change the prototype pointing to Object.setProtoTypeof () Object.setProtoTypeof MDN

  • getter setter

  • Object.create
      
      function Person(name,age){
          this.name = name
          this.age = age 
      
      }
      
      Person.prototype.sayName = function(){
          console.log(this.name)
      }
      
      Person.prototype.one = function() {return1}let person = new Person('alex'18),let student = Object.create(person)
      
      
      //for inYou can iterate over methods and properties on the prototypefor(let keyStu in student){
          console.log(keyStu, student[keyStu])
      }
      console.log(student.time)
      
      student ={
          name: 'tom',
          age:'20'} console.log(student) // only iterate over its own properties and methodsfor(let key in student){
          if(student.hasownProperty (key)){console.log(key, student[key])}} //function SuperClass() {} / /function OtherSuperClass() {} / /function MyClass() { // SuperClass.call(this); // OtherSuperClass.call(this); Prototype = object.create (superclass.prototype); Other / / / / / / mixed Object. The assign (MyClass. Prototype, OtherSuperClass. Prototype); / / / / to specified constructor / / MyClass prototype. The constructor = MyClass; // MyClass.prototype.myMethod =function() {/ / / /do a thing
      // };
    Copy the code

  • The difference between an empty Object declared by a literal and object.create (null)

  • Object application:

    • Avoid writing multiple if else:
// According to different status codes, prompt different messageslet nowCode = 2
switch(nowCode){
    caseZero:case 1:
        alert('success')
        break
    case 2:
        alert('failure')
        break
    case 4:
        alert('On request')
        break
    default:
        alert('Unknown status code'Key: status code value: attributes of the statueCode objectfunction judgeCodeStatus(nowCode = 0){
    let statueCode  ={
        0 : 'success', 1:'success', 2:'failure', 4:'On request'
    }
    if(statueCode[nowCode]){
        alert(statueCode[nowCode])
    }else{//defalut alert('Unknown status code')
    }
}
judgeCodeStatus(prompt('Please enter status code'))


Copy the code
Let student = {'name' :'lili', 'age' : 18, math: 100, English: 90} 'Copy the code

  • Object deconstruction: easy to quickly value

  • Base types are passed by value, and reference types (arrays of objects) are passed by reference. After modification, all values that use the reference change

15, class

  • Object oriented, class writing, is essentially syntactic sugar based on prototype chains

    • Define a class: the class keyword

    • The static method on a class, static, is equivalent to the method on a constructor, passing through the class without using new. Method name use

    • Class constructor: Properties used to initialize instances

    • The method on the class is equivalent to the method on the prototype: it is used to add the method on the prototype for multiple instances to use, the method is defined on the prototype, through the prototype chain search, saving memory

    • Inheritance of classes: extends keyword

    • How does the ES5 writing define a constructor and add methods and instantiated objects to the prototype

    
    functionPersonEs5(name,age){this.name = name this.age = age} // Add its own method to the constructor object persones5.hello =function(){console.log(1)}
    
    PersonEs5.prototype.sayName = function() {returnThis.name} // Multiple methods continue in persones5.prototype.xx =functionThe //new + constructor instantiates an instance p1let p1 = new PersonEs5('alex'Console. log(p1) // The sayName method of p1 itself does not find the corresponding prototype chain, Find the method console.log(persones5.hello ()) on the constructor using console.log(p1.sayname ()) // printCopy the code

  • Es6 writing:

  • Put the code to the right of Babel in vscode for easy view and analysis of the code

  • So essentially class is syntactic sugar

Xvi. String

  • Literal creation, single or double quotation marks

17 regular expressions, processing string tool TODO after the complete complement

  • For example
    let str = '0123123123helloworld'; // Find all numbers without using the reletnum = [...str].filter( s => ! Number.isNaN(parseInt(s))).join("") console.log(num)//0123123123 // Use the regular console.log(str.match(/\d/g).join("")) / / 0123123123Copy the code
  • How to create
    • Literal way:
    • New Regexp mode:

17, built-in object, know when to find the corresponding object

  • Number
let str = '123', str1 = '12.3'
console.log(Number(str), Number.parseFloat(str1))
console.log(Number.isNaN(str))
letNum = 12.324234let numStr = num.toFixed(2)
console.log(numStr)

console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MIN_SAFE_INTEGER)
console.log(Number.MAX_VALUE)
console.log(Number.POSITIVE_INFINITY)
console.log(Number.NEGATIVE_INFINITY)

Copy the code

  • Math
Console. log(math.pi)//3.141592653589793 // Absolute value console.log(math.abs (-1)) //1 Console. log(math.sin (math.pi /2)) //1 // round up console.log(math.ceil (.99)) //1 // round up console.log(math.floor (1.99)) //1 // random number Returns a pseudo-random number between 0 and 1. Console. log(math.random ()) // returns a number to the y power. Console. log(math.pow (10,2))//100 // returns the integer part of a number, directly removing the decimal point and the following part. The console. The log (math.h trunc (9.45)) / / 9Copy the code
  • Date
    //Date
    letdate = new Date() //get console.log(date) console.log(date.getFullYear()) // 2020 console.log(date.getMonth()) // 4 + 1 Log (date.getday ())// Day of the week 0 console.log(date.getdate ())// 10 console.log(date.gethours ())// 20 Console.log (date.getminutes ()) //56 console.log(date.getseconds ()) //32 // 1970 Milliseconds from now console.log(date.gettime ()) //1589115447269 // Console. log(date.tolocaledateString ()) //2020/5/10 //set 
    console.log(date.setFullYear(2030))
    console.log(date.toLocaleDateString())//2030/5/10
    
    date.setTime(1404648371937)
    console.log(date.toLocaleDateString())//2014/7/6
Copy the code
  • Json
    • Parse JSON String to JSON object
    • Json. stringify string-ify the JSON object
        let postJSON = `{
        "id" : 1,
        "title" : "Title"."comments":[
            {
                "userId": 1,"comment":"Comments 1"
            },
            {
                "userId": 2."comment":"Comments 2"}]."isPublished" : false."author"Parse (postJSON) : null} '// convert to json object console.log(json.parse (postJSON))let JSONObj ={
        name:'alex',
        skills:['js'.'html'.'css'}} console.log(json.stringify (JSONObj)) // Format console.log(json.stringify (JSONObj, null, Const isJSON = (jsonStr)=>{if(typeof jsonStr  ==='string'){
            try{
                if(typeof  JSON.parse(jsonStr)){return true}
            }catch(e){
                return false
            }
        }
    }
    console.log(isJSON(postJSON)) // true
    Copy the code

  • SetA collection with no repeating elements
/ / Set the curdlet,1,2,3,3,4,4 arr = [1] the console. The log (new Set (arr) [...]) / / array to heavy [1, 2, 3, 4]let set = new Set()
    set.add(1)
    set.add(2)
    set.add(4)
    console.log(set)// Set(3) {1, 2, 4} set.add(4)// Adding duplicate elements does not take effect console.log(set) / / Set (3) the {1, 2, 4} / / determine whether contain the console log (Set) from the (2), the Set. From the (10)) / /true falseForEach (val => console.log(val)) //1 2 4set ,set.size)//Set(0) {} 0
    
    //setThe elements inside are objectslet obj1 = {id :1} , obj2 = {id:1}
    set.add(obj1)
    set.add(obj2)
    console.log(set)
    set.add(obj1)
    console.log(set)
Copy the code

  • Map: is a key-value data structure similar to an object, but a map’s key and value can be of any type

    let map = new Map()
    let objKey = {key : 2}
    map.set(1,'val1')
    map.set( objKey ,'val2')
    map.set('key 3'.'val 3'Console. log(map.get(1), map.get(objKey), map.get(objKey), console.log(map.get(1), map.get(objKey), map.get('key 3'),
             map.get('123'Console. log(map.has(objKey)) //val1 val2 val 3 undefined // Check whether there is a Boolean returned by key console.log(map.has(objKey)) //trueMap.foreach ((val, key) => console.log(key, val)) // iteratorlet iterator = map.entries()
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    console.log(iterator.next())
    
    //forOf traversalfor(let [key, val] of map){
        console.log(key, val)
    }

Copy the code

Xviii. Exception Handling

  • try{}catch(e){}finally{}
  • throwActively throwing an exception
  • Program error exception
  • How do I customize exceptions?
  • How do I handle multiple exceptions?
       // ok always
    try{
        console.log('ok')
    }catch(err){
        console.log(err)
    }finally{
        console.log('always'} // err always throws an exception. Try {throw new Error()'diy err')
        console.log('ok')
    }catch(err){
        console.log(err)
    }finally{
        console.log('always'} class ErrorApi extends Error{constructor(url,... args){ super(... args) this.url = url this.name ='errorApi'}}function getPostData( url = '/post/blogs', code = '404'){
        console.log('Start getting data... ')
        throw new ErrorApi(url, code)
    }
    
    try {
        getPostData()
    } catch (e) {
        let{name, url, Message} = e console.log(e) console.log(name, URL,message)} console.clear() // Custom exception class ErrorApi extends Error{ constructor(url , ... args){ super(... args) this.url = url this.name ='errorApi'}}function getPostData( url = '/post/blogs', code = '404'){
        console.log('Start getting data... ') console.log(aaa) throw new ErrorApi(URL, code)} try {getPostData()} catch (e) {// instanceof handles different types of exceptionsif( e instanceof ReferenceError){
            console.log('Program exception')}else if(e instanceof ErrorApi){
            console.log('abnormal API')}}Copy the code

  • Handling multiple exceptions

  • 19. Asynchronous

Js code can be divided into synchronous and asynchronous. Synchronous code is a time-consuming operation, and the synchronization will wait until it is completed. Asynchronous code will not wait, and will return the result to the synchronous execution place after the completion of execution elsewhere

  • setTimeout
    //setTimeout Indicates that the command is executed in secondslet timer1 = setTimeout(()=> console.log('Execute after 1s'), 1000)
    console.log(timer1)
    console.log('First line of code')
    console.log('Line 2') //clearTimeout + timerId interrupts code executionsetTimeout( ()=>{
        if(timer1){
            clearTimeout(timer1)
            console.log('Execution of timer1 is interrupted')}}, 500)Copy the code

  • setInterval
    //setInterval Specifies the number of seconds in which the Interval is executedlet intervalId = setInterval( ()=>{
        let date = new Date()
        console.log(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}')},1000) // Stop after 15 secondssetTimeout(()=>{
        intervalId && clearInterval(intervalId)
    },15000)
Copy the code

  • Promise
//Promsie + thenSuccessful handlinglet delay = (time) => new Promise( succ =>{
    setTimeout( ()=>{ succ('success after ' + time * 1000)}, time * 1000)
})

console.log(1)
delay(2).then( res => console.log(res))
console.log(2)
Copy the code

Let delay = (time) => new Promise((succ,fail)=>{setTimeout(()=>{fail('fail after '+ time * 1000)}, Log (1) delay(2). Then (res => console.log(res)) //. Catch (err => console.log(err +)) // An error is caught console.log(2) ```Copy the code

    let delay = (time) => new Promise( (succ ,fail)=>{
    setTimeout( ()=>{ fail('fail after ' + time * 1000)}, time * 1000)
})

console.log(1)
delay(2).then( res => console.log(res))
        .catch( err => console.log(err + 'Catch an error') // Catch error console.log(2)Copy the code

  • The chain calls promise
// the promsie chain call catch can be written lastthen// console.log('strat')
    // new Promise( (resolve, reject)=>{
    //     setTimeout(()=>{
    //         resolve(1)
    //     }, 1000)
    // }).then( res =>{
    //     console.log(res) //1
    //     return res + 10
    // }).then( res =>{
    //     console.log(res) //11
    //     return new Promise( resolve => resolve( res + 20))
    // }).then( a =>{
    //     console.log(a) //31 
    // })
    // console.log('end') / /thenCatch will later return a new promise //promsie catch can catch the promsie in the promise orthenThe error in it can be written in the last onethenThe back of the console. The log ('strat')
    new Promise( (resolve, reject)=>{
        setTimeout(()=>{
            // reject('reject in 1'Resolve (1)// resolve(1)// resolve(1)// promsie (1)// throw). Then (res =>{console.log(res) //1 throw'then abnormal'
        return res + 10
    }).then( res =>{
        console.log(res) //11
        return new Promise( resolve => resolve( res + 20))
    }).then( a =>{
        console.log(a) //31 
    }).catch( err =>{
        // console.log(err)//reject in 1
        console.log(err)//thenAbnormal}) console. The log ('end')
Copy the code
  • Multiple promsie use promise.all
        let p1 = new Promise( resolve =>{
        setTimeout( ()=>{
            resolve(1)
        },1000)
    })
    
    let p2 = new Promise( resolve =>{
        setTimeout( ()=>{
            resolve(2)
        },1000)
    })
    
    
    let p3 = new Promise( resolve =>{
        setTimeout( ()=>{
            resolve(3)
        },1000)
    })
    
    Promise.all([p1, p2, p3])
            .then( res =>{
                let [a,b, c] = res
                console.log(a,b,c)
            })
Copy the code

  • Async /await beautifies asynchronous code
    console.log(1)
    async function as1() {setTimeout( ()=>{
            console.log('AS1 completed')
        },1000)
    }
    as1()
    console.log(as1() )
    console.log(2)
Copy the code

    async function as1(){
        try {
            let result2  = await as2()
            let result3  = await as3()
            console.log(result2) // 10 
            console.log(result3) // 333 
        
        } catch (e) {
            console.log(e)
        }
    }
    
    async function as2() {return new Promise( resolve =>{
            setTimeout( ()=>{
                resolve(10)
            }, 1000)
        })
    }
    
    async function as3() {return new Promise( resolve =>{
            setTimeout( ()=>{
                resolve(333)
            }, 500)
        })
    }
    as1()
Copy the code

Modular TODO

What’s the next step?

- DOM - AJAX - Framework learning - Backend exploration? - Keep learning, keep practicingCopy the code

References:

  • mdn
  • stackoverflow
  • Fenghua front-end B station thanks for such a high-quality video!!
  • Google + personal understanding