Detailed introduction to JS-ES6

let and const

let

Block level scope: a scope that is common in all languages;

    {
      var a = 10;
      let b = 20;
     }
     console.log(a)//10
     console.log(b)// b is not defined

Variables declared with let in a brace are not externally accessible, and each brace is an independent scope

With the let declaration, we cannot access i outside the function, and i only exists in the for loop as a subscript. Therefore, each i is independent at this time; We can easily get the subscript of the current element when clicking, without doing a lot of tedious processing

var aLi = document.querySelectorAll("li");
for(let i = 0;i<aLi.length;i++){
  aLi[i].onclick = function(){
    alert(i);
  }
  console.log(i);//0  1  2  3
}

In JS, a variable declared by var has declaration elevation, which is a defect in JS. However, the current let does not have declaration elevation

        // console.log(a);//undefined
        // console.log(b);//b is not defined
        // var a = 10;
        // let b = 20;
        let a = 20;
        function foo(){
            console.log(a);
            let a = 10;
        }
        foo();//a is not defined
        //Error reporting, temporary dead zone
        //js found a local a during precompiling, so we won't look for the global a
        //However, during execution, he finds that the local a is declared by the following let, so an error is reported

ES6 specifies that in a block, once a variable is declared with let or const, the block will become a block level scope. The variable declared with let or const is bound to the block and is not affected by any variable. Cannot be used before the variable is declared with let. Grammatically, we call this a temporary dead zone (TDZ)

const constant

Declare constants:

const a = 20;//Constants: quantities that cannot be modified
a = 30;    
//Uncaught TypeError:Assignment to constant variable. (uncaught type error: assignment to constant variable)
console.log(Math.PI);//3.141592653589793
        Math.PI = 4;
        console.log(Math.PI);//3.141592653589793
const arr = [2,3,4,5];
        //arr = [3,4,4,6];
        //You cannot modify the array or object reference, but you can modify the internal structure through the API
        arr.push(6,7);
        console.log(arr);//[2, 3, 4, 5, 6, 7]

Extended operators

Three period signs. The function is to expand an array or array like object into a series of values separated by commas

var arr = [1,2,3,4,5];
        console.log(arr);//Array(5)
        console.log(...arr);//1 2 3 4 5   console. The log does not display commas. In fact, there are commas in the middle
        function add(arr){
            arr.pop();
            console.log(arr);
        }
 var foo = function(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
var arr = [1, 2, 3];
//Traditional writing
foo(arr[0], arr[1], arr[2]);
//Use extended operators
foo(...arr);
//1
//2
//3

rest operator

The rest operator is also a three dot operator, but its function is just the opposite to that of the extension operator. It combines a comma separated sequence of values into an array

 //It is mainly used for indefinite parameters, so ES6 can no longer use the arguments object
var bar = function(a, ...args) {
    console.log(a);
    console.log(args);
}
bar(1, 2, 3, 4);
//1
//[ 2, 3, 4 ]

String extension (understand)

1. Unicode representation of string; The rule is \u + four hexadecimal digits;

 //For example: console log("\u0061");

The print result is a;

This new character representation can only represent numbers between \u 0000 and \u ffff. If it is out of range, it must be represented by double bytes;

  console.log("\uD842\uDFB6"); 

The print result is_
If you are not familiar with writing according to the rules, such as console log("\uD842\uDFB69")
This 9 is an extra character; Then it is considered that this segment of characters is \D842uDFB6+9, so the print result is 9;

If we want to represent characters that are out of range at one time, we can use {} to represent them;
For example:
console.log("\u20BB9"); The print result of this is split ₻ 9
console.log("\u{20BB9}"); The result of this print is a complete character

ES6 supports character representation in multiple formats;

String template extension:

There is a new string in ES6, which is represented by (the character on the wavy line > backquote);

Usually, we want to splice a string with a label in this way:

      bianliang + " <strong>This is a word" + obj.name + "</strong> " + bianliang

But with ES6 strings, everything becomes very simple;

      `  ${bianliang} <strong>This is a word ${obj.name}</strong>${bianliang} `

Expanding variables with ${} makes splicing very easy;
Very simple line feed;

      `In JavaScript \n is a line-feed.`     
      console.log(`string text line 1
      string text line 2`);

When we want to use 'backquotes' in a string, we need to escape;

      `\`Yo\` World!`    //"`Yo` World!"

Templates can also call functions;

      function fn() {
      return "Hello World";
}
      `foo ${fn()} bar`

New method of string:

repeat() repeat function

 'x'.repeat(3)  //xxx;
  Duplicate string;

includes() startsWith() endsWith();

Determine whether a string exists in the string;

var s = 'Hello world!';

s.startsWith('Hello') // true starts with a parameter

s.endsWith('!') // true ends with a parameter

s.includes('o') // true includes parameters;

The second method accepts the second parameter, and the second parameter indicates the starting position;

  var s = 'Hello world!';

  s.startsWith('world', 6) // true

  s.endsWith('Hello', 5) // true

  s.includes('Hello', 6) // false

for of

A new traversal method;
for of can be used to traverse strings:

      var s = "abc";
      for(let  b of s){
           console.log(b) // "a"  "b"  "c"
       }

=>Arrow function

var test = function(x){
    return x+2;
}

Use the arrow function: VAR test = x = >x+2;
var function name = parameter = > operation rule;

If the arrow function has only one formal parameter, you can omit the parentheses

    var foo = str => {
    console.log(str);
            }

If the function body has only one sentence, you can omit the braces

    var foo = str => console.log(str);

If there is only one sentence and the sentence is return, you can omit the return keyword

var foo = str => str+"abc";
console.log(foo("fooo"));

The arrow function will automatically bind this (the arrow function does not have its own this)

document.querySelector("button").onclick = function(){
                setTimeout(() => {
                    console.log(this);
                },1000);
            }

defect

First: the arrow function cannot be new. Its original design intention is different from that of the constructor
Second: if the arrow function wants to return a JSON object, it must be enclosed in parentheses var test = () = > ({id:3, val=20})

Destructuring assignment

var obj = {name:"lisi", age:80, gender: "female"};
            var {age, name, gender="male"} = obj;
            console.log(age, name, gender); 
            
var json = [
    {name:"lisi", age:80, gender: "female"},
    {name:"liwu", age:70, gender: "male"},
    {name:"liliu", age:60, gender: "female"}
        ]
            
var [{age},{name},{gender}] = json;
    //var {name} = b;
    console.log(name);

Symbol type the sixth basic data type symbol

The Symbol function generates a unique value. It can be understood that the Symbol type is close to the string, but the unique value is generated every time, that is, it is not equal every time. As for how much it is equal, it does not matter. This is useful for some dictionary variables

var s1 = Symbol();
var s2 = Symbol();
var s3 = Symbol("abc");
var s4 = Symbol("abc");

s1 Not equal to s2
s3 Not equal to s4

Case of using Symbol type: click div to change color

var obj ={
                red: Symbol(),
                blue: Symbol(),
                green: Symbol(),
                yellow: Symbol()
            }
            var color = obj.red;
            //Applicable to the only concerned state (to which state)
            //But don't know the internal structure (don't care about the value)
            document.querySelector("div").onclick = function(){
                if(color === obj.red){
                    this.style.background = "blue";
                    color = obj.blue;
                }else if(color === obj.blue){
                    this.style.background = "green";
                    color = obj.green;
                }else if(color === obj.green){
                    this.style.background = "yellow";
                    color = obj.yellow;
                }else if(color === obj.yellow){
                    this.style.background = "red";
                    color = obj.red;
                }
            }

Set and Map structures

set

The Set set is de duplicated by default, but the premise is that the two added elements are strictly equal, so 5 and "5" are not equal, and the strings from two new are not equal

A Set is essentially a wrapper around an array. For example:

 let imgs = new Set();
imgs.add(1);
imgs.add(1);
imgs.add(5);
imgs.add("5");
imgs.add(new String("abc"));
imgs.add(new String("abc"));
// Printed results: 15'5''abc''abc'

The following shows a very sophisticated method of array de duplication

var newarr = [...new Set(array)];

Set set traversal:

1. traverse according to KEY

 var imgs = new Set(['a','b','c']); 
 //Traverse by KEY
for(let item of imgs.keys()){
    console.log(item);
} //a //b //c

2. traverse according to VALUE

 //Traversal by VALUE
for(let item of imgs.values()){
    console.log(item);
} //a //b //c

3. traverse according to KEY-VALUE

for(let item of imgs.entries()){
    console.log(item);
 } //['a','a'] //['b','b'] //['c','c']

4. normal for... of loop

 //Normal for Of loop (the difference between for...of and for in is obvious, that is, the direct value is obtained instead of the subscript)
for(let item of imgs){  
  console.log(item);
} //a //b //c

map

Map set, i.e. map

 let map = new Map();
map.set("S230", "Zhang San");
map.set("S231", "Lisi");
map.set("S232", "Wang Wu");
map.get("s232"); // Get an element king five
for(let [key,value] of map)
{console.log(key,value);}
 //Loop traversal with deconstruction assignment 

class in French (understand)

Class reserved word finally becomes keyword
Previously wrote a constructor (class)

function Pad(color){
    this.color = color;
}

Now the writing method is closer to Java

class Iphone{
    constructor(color, size){
            this.color = color;
            this.size = size;    
     }    
playgame(){
           //.............    
}    
toString(){
          return `The color of this phone is ${this.color} Screen size is ${this.size}`;
    }
}

We define a class named Iphone, and generate an instance through the class: var iphone = new Iphone("white", 5);

The constructor is called the constructor. When we create a new object, it is automatically called

However, in essence, JS is still implemented using prototypes. That is to say, this is just a new writing method, which is no different from the previous constructor.

Note that class is used to define a class, which must be defined before use

Tags: Javascript ECMAScript

Posted by bryanptcs on Thu, 11 Aug 2022 22:41:03 +0530