Example analysis of new knowledge points of string, array, object and function in ES6 learning notes


In this paper, an example is given to illustrate the new knowledge points of string, array, object and function in ES6 learning notes. To share with you for your reference, as follows:

1. Template string

Inside the quotation mark is used to input the formatted string text. Within the quotation mark, the expression can be included with ${}

let str=`
    <!DOCTYPE html>
      <html lang="en">
            <p>Format string</p>

2. Convert to array

Array.form converts pseudo array and collection to array

let allLi=document.querySelectorAll('li');
Console. Log (array. Isarray (allli)); // output false, allli is not an array
let arr=Array.from(allLi);
Console. Log (array. Isarray (ARR)); // output true, arr is converted to array

Array.of builds elements as arrays

Let arrayof = array. Of ('str ', 2, {}); // create an array of strings, numbers, and objects
Let arr = array. Of (7); // array contains an element 7
Let arr = array (7); // array contains 7 empty elements

3. Encapsulation of class

Wrapping classes by class

class Person{    
    Constructor (name, age) {// constructor of person class
     Print() {// class function output
      console.log("My name is "+this.name+",I'm "+this.age+" years.");
  let p=new Person('tony',15);

4. Use of objects

When a variable is used as an element of an object, the variable name is used as the key value and the variable value is used as the value

let name='tony';
let age=15;
let person={

The output result is:

Object { name: “tony”, age: 15 }

The object. Assign () method implements object merging. The parameters are: merge target, merge source 1, merge source 2

let obj1={'name':'tony'};
let obj2={'age':15};
Let obj 3 = {'sex': 'male'};
let obj={};
Object. Assign (obj, obj 1, obj 2, obj 3); // add the following objects to the first object

Output is:

Object {Name: “Tony”, age: 15, sex: “male”}

5. Extend operator

Split the whole string, object, etc. into single elements

Let STR = "this is a string";
let arr=[...str];

Output is:

6. Function rest parameter

When the number of parameters passed in is uncertain, the method of “… Parameter” can be adopted, and then each parameter can be traversed

function sum(name,...num) {
    let res=0;
    For (let value of Num) {// traverse the unknown number of parameters as array num
    return res;

7. Arrow function

Arrow function can simplify function (parameter) {expression} to: (parameter…) = > {expression…} without inputting function, or even omitting (), {}, return.

1. When there is only one parameter, it can be written as a parameter = > expression. For example, use the map function to traverse an array and multiply each element by 2:

var arr = [1, 4, 9, 16];
Const MAP1 = arr.map (x = > x * 2); // use map() to traverse the array, pass in a parameter as X, and return x * 2

The function in map traverses the elements in each arr with X as the parameter, * 2 and then returns automatically to form the MAP1 array

2. When there are multiple parameters, you need to parenthesize them: () = > expressions, such as traversing array output indexes and values:

let arr=['data0','data1','data2'];
Arr.foreach ((value, index) = > // traverse the array through foreach, passing in two parameters, value and index

The output is as follows:

3. When there are multiple lines of expressions, to use {} to contain the function into a block: () = > {}, and when using block statements, the function will not automatically return a value, you need to use return to return the value.

4. The {} of JavaScript can also represent an object. When using the arrow function to return an object, in order to be different from the function body, you need to include the object with (): () = > ({}). Otherwise, an error will be reported. For example, when using the setstate method in react, you need to return an object:

this.setState((prevState) =>({
  flag: !prevState.flag

8. Promise function

When using the interface call, it is sometimes necessary to call different functions according to the success of the call return. ES6 provides the promise function to solve this problem. When the call succeeds, execute the. Then method, and when it fails, execute the. Catch method to handle different situations and return different data.

For example, define a promise method to check login. When the incoming parameter is true, the login succeeds, the callback function is then, and false fails. Call catch:

//Define promise function
    let checkLog=function (flag) {    
     return new Promise(function(resolve,reject){
      If (flag) {// if the condition is true, execute the resolve function
       Resolve ({// the parameters in parentheses are returned as the result
        Info: "login succeeded"
      }Else {// false reject
        Info: "login failed"
    //Using the promise function
    Checklog (false). Then (RES = >
     Console. Log (` success information: ${res.info} ');
     Console. Log (` error message: ${err. Info} ');

When true is passed in:When false is passed in:

Interested friends can useOnline HTML / CSS / JavaScript code running tool: http://tools.jb51.net/code/htmljsrun test the running effect of the above code.

For more information about JavaScript, please refer to our special topics: introduction to JavaScript object-oriented course, summary of JavaScript errors and debugging skills, summary of JavaScript data structure and algorithm skills, summary of JavaScript traversal algorithm and skills, and summary of JavaScript mathematical operation usage

I hope this article will be helpful for you to design JavaScript programs.