Some knowledge points of ES6

1. Define variables / constants

1) . let defining variables

1. Function:
  *Similar to var, it is used to declare a variable
2. Features:
  *Valid in block scope
  *Cannot repeat declaration
  *No preprocessing, no promotion
3. Application:
  *Loop traversal plus monitor

  *Replacing var with let is the trend

2) . const defining constants

1. Constants are generally considered to remain in a state for a long time and should not be modified
2. Defining constants in ES5 also uses var, but there is no real meaning to implement constants, which can be modified
3. const is defined. The defined constant cannot be modified

3) . deconstruction and assignment of variables

-Deconstruction: resolving the structure of the target object

-Assignment: get data after parsing structure

let {n, a} = {n:'tom', a:12}
let [a,b] = [1, 'atguigu'];

Used to assign multiple parameters

4) . arrow function

*No parameters: () = > console. Log ('xxxx ')
*One parameter: I = > I + 2
*Greater than one parameter: (I, J) = > I + J

*Function body without braces: return result by default
*If there is more than one statement in the function body, it needs to be surrounded by {}. If there is something that needs to be returned, it needs to be returned manually

5) Dot operator

function add(...values) {
  let sum = 0;
  for(value of values) {
    sum += value;
  return sum;

Variable parameter, used to replace arguments but more flexible than arguments, can only be the last parameter

6) Parameter defaults

When no parameter is passed in, the default value in the parameter is used by default

function Point(x = 1,y = 2) {
this.x = x;
this.y = y;

7) Promise object

Promise object: represents an event that will happen in the future (usually an asynchronous operation)

With promise objects, asynchronous operations can be expressed in a synchronous process, avoiding nested callback functions (commonly known as "callback hell")
*Promise of ES6 is a constructor used to generate promise instances

//Create promise object

  let promise = new Promise((resolve, reject) => {
    //Initialize promise to pending
    //Perform asynchronous operation

    if(Asynchronous operation succeeded) {
      resolve(value);//Modify the status of promise fully filled
    } else {
      reject(errMsg);//Modify the project status to rejected


//Call then() of promise
    result => console.log(result),
    errorMsg => alert(errorMsg)

Three states of Promise object

*pending: initialization status
 *Fully filled: success status
 *rejected: failed state
//Timeout processing with Promise object

function getNews(url) {
    //Create a promise object
    let promise = new Promise((resolve, reject) => {
        //Initialize promise to pending
        //Start asynchronous task
        let request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if(request.readyState === 4){
                if(request.status === 200){
                    let news = request.response;
                    reject('The request failed...');
        request.responseType = 'json';//Set the data type returned"GET", url);//Specify the method of request, create link
        request.send();//Send out
    return promise;

        .then((news) => {
            console.log('http://localhost:3000' + news.commentsUrl);
            return getNews('http://localhost:3000' + news.commentsUrl);
        }, (error) => {
        .then((comments) => {
            document.write('<br><br><br><br><br>' + JSON.stringify(comments));
        }, (error) => {

8).Symbol property

The attribute names of objects in ES5 are all strings, which is easy to cause duplicate names and pollute the environment

In ES6, a kind of original data type symbol is added (existing original data types: String, Number, boolean, null, undefined, object)

Characteristics of Symbol attribute

1. The value corresponding to the Symbol property is unique. Solve the problem of naming conflict

2. Symbol value cannot be calculated with other data, including string concatenation

3. for in, for of does not traverse the symbol property.

9) iterator traverser

Iterator is an interface mechanism that provides a unified access mechanism for different data structures. The iterator interface is mainly used for...of consumption.

How the Iterator interface works

1. Create a pointer object that points to the beginning of the data structure.
2. The next method is called for the first time, and the pointer automatically points to the first member of the data structure
3. Call the next method continuously, and the pointer will move backward until it points to the last member
4. Each call to the next method returns an object containing value and done, {value: the value of the current member, done: Boolean}
          Value indicates the value of the current member, and the Boolean value of done indicates whether the structure of the current data is traversed.
          When the traversal ends, the value returned is undefined, and the value of done is false
function mockIterator(arr) {
  let nextIndex = 0; // Record where to access the data structure
  return {
    next: function () {// Traverser object
      return nextIndex<arr.length?{value: arr[nextIndex++], done: false}:{value: undefined, done: true} // Dynamic return of traversal result data

let arr = [1,2,3,4,5];
let iteratorObj = mockIterator(arr);

10) . Generator function
What is the Generator function

1. One of the solutions of asynchronous programming provided by ES6

2. The Generator function is a state machine, which encapsulates data in different states,

3. Used to generate iterator objects (iterator interface)

4. Function can be paused (lazy evaluation), yield can be paused, and next method can be started. Each time the expression result after yield is returned

function* generatorTest() {
  console.log('Function start execution');
  yield 'hello';
  console.log('Restart after function pause');
  yield 'generator';
// Generate traverser object
let Gt = generatorTest();
// Execute function, pause when yield is encountered
console.log(Gt); // Traverser object
let result =; // Function execution, yield pause encountered
console.log(result); // {value: "hello", done: false}
result =; // Function starts again
console.log(result); // {value: 'generator', done: false}
result =;
console.log(result); // {value: undefined, done: true} indicates that the internal state of the function has been traversed

11).for of loop

let arr = [1,2,3,4,5];
for(let num of arr){

let set = new Set([1,2,3,4,5]);
for(let num of set){

let str = 'abcdefg';
for(let num of str){

let btns = document.getElementsByTagName('button');
for(let btn of btns){

Tags: Front-end JSON Attribute Programming

Posted on Wed, 29 Apr 2020 01:00:32 -0700 by deeppak