Introduce ES6

What is the ES6

  • ECMAScript 6 or ES6 for short. Is the next generation standard of the javascript language. Its goal is to make the JavaScript language usable for writing complex, large-scale applications as an enterprise-level development language. It is a language standard, with 6 indicating a version number.

  • Technical Committee 39 of ECMA (European Computer Manufacturers Association), The organization responsible for developing the ECMAScript standard, TC39, publishes a version of ECMAScript every year:

    • ES2015: Called ES6.

    • ES2018: www.ecma-international.org/ecma-262/8….

    • ES2019:www.ecma-international.org/ecma-262/9….

  • ES6 in relation to javascript: ECMAScript is a language standard that javascript implements (as well as JScript and ActionScript).

    • In November 1996, —– Netscape, the creator of javascript, decided to submit javascript to ECMA in order to make it an international standard.

    • In 1997, ECMA released the ECMA-262 standard, which defines the browser scripting language as ECMAScript. This version is known as version 1.0.

    • This standard was originally developed for the javascript language, but it is not called javascript for the following reasons:

      • The trademark. Javascript itself has been trademarked by Netscape.

      • ECMA is more open and neutral than javascript.

  • Relationship between ES6 and ECMAScript2015

    • ECMAScript2015 is the release of ECMAScript2015 specifically until June 2015.

    • ES6 has two meanings

      • Especially ECMAScript2015

      • General reference to new features in ES2015 and later, although later releases should be called ES2018, ES2019… Es6.

Learning content

Es6 has added a number of powerful syntaxes, some of which are commonly used:

  1. Let and const

  2. Deconstruction assignment

  3. Function extension

  4. String extension

  5. Array extension

  6. Short for object

For other content, you can supplement it by yourself.

To study the reference

  1. Support for ES6 in various environments: Kangax.github. IO /compat-tabl…

  2. ES6 ebook: es6.ruanyifeng.com/#docs/intro

Let and const

The keyword we used to define variables was var. The variables defined by var have many strange characteristics. The following two points stand out:

  • Variables are used before they are defined —— variables are promoted.

    console.log(a);
    var a = 1;
    console.log(a)Copy the code
  • Lack of block-level scope.

    // Define a loop variable I here to use the loop.
    for(var i=1; i<10; i++){}// I can also be used outside of the loop body.
    console.info(i);Copy the code

Both of these questions can be confusing for beginners, as well as for programmers coming from other languages. To address these issues, LET has been added to ES6.

The reason ES6 introduced const is because ES5 does not provide constants.

Let the variable

Function: Defines variables. (Var is also used to define variables)

Basic use of let

Format: let variable name = value;

It is used to define variables in the same format as the var keyword. Change to let where var can be used.

Differences with VAR

  • You can’t define it twice

  • There is no variable promotion (var definition is variable promotion), must be defined before use

  • Global variables are not attached to the properties of the window object

  • Has block-level scope

You can’t define it twice
// 1. Let defines variables. Variables cannot be defined again
let name = 'zhangsan';
name = 'lisi';
console.log(name); // lisi
let name = 'wangwu'; Identifier 'name' has already been declaredCopy the code
Block-level scope

scope

  • Global scope

  • Local scope

  • Block-level scopes (proposed in ES6)

If variables are defined by the let keyword, scope can be shard in JS code with {}.

// has block-level scope. Blocks are braces
{
    let age = 18;
    console.log(age); / / 18
}
console.log(age); // There is no age definition in this scope// block level scope nesting
{
    let a = 1;
    {
        let a = 2;
        console.log(a);
        a = 3;
        console.log(a);
    }
    console.log(a)
}
​
// Hidden block-level scope
for (let i = 0; i < 10; i++) {
    // I can only be used in this scope because of block-level scope
}
console.log(i);  // There is no age definition in this scopeCopy the code
No variable promotion

Variables defined by let no longer have variable promotion and must be defined before they are used

console.log(gender); // Error: Gender has not been defined yet
let gender = 'male'; 
​
console.log(1); // output undefined without error
var a = 1; Copy the code

Global variables are not assigned to the window object

Global variables declared by the let are not appended to the Window object as properties and are no longer related to the window object.

let hobby = 'eat';
var a = 1
console.log(window.hobby); 
console.log(window.a); Copy the code

Support for var remains in ES6, and you can use both var and let in your code. Of course, let is recommended.

Const constants

Usage scenarios

When programmers collaborate on a project, they encounter a situation where there is some data that everyone needs but cannot modify, that is, the data is read-only. For example, when developing a company’s website, the company’s basic information: address, company name, phone number, etc., can be used in multiple places, but it is not allowed to change. It is shown that using variables to hold this information is not appropriate because variables are not read-only. In this case, we can store the data in constants.

Syntax and naming conventions

Function: Defines a read-only constant.

Format: const constant name = constant value;

Const COMPANY_NAME = “XXX company”

Note:

  • Unlike variable names, constant names are usually all uppercase, with multiple words separated by an _ underscore.

Characteristics of const

A constant is one that cannot be modified, i.e. :

  • Once defined, it cannot be changed;

  • Once declared, it must be initialized immediately;

const a = 1;
a = 2; / / an errorCopy the code

Other characteristics similar to LET

  • Has block-level scope

  • There is no variable promotion and it must be defined before it is used

  • Constants are also independent and are not pushed into the window object after definition. They are not properties of the window object

nature

What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored at the memory address to which the variable points cannot be changed.

const obj = {a:1};
obj.a = 2;
console.log(obj); // Question: is the attribute value a of the obj object changed?Copy the code
  • For data of simple types (values, strings, booleans), the value is stored at the memory address to which the variable points and is therefore equivalent to a constant value.

  • In the case of composite types, such as objects and arrays, a variable points to a memory address that holds only a pointer to the actual data. Const guarantees that the pointer is fixed, but does not control whether the data structure it points to is mutable. Therefore, great care must be taken to declare an object as a constant, and its properties can be modified.

If you really want to define an Object that cannot be modified (attributes cannot be added, modified, or deleted), you can use object.freeze (). It is a function that can freeze an object completely:

function makeConst(obj){
    Object.freeze(obj);
    Object.keys(obj).forEach(function(key){
        if(typeof obj[key] === 'object'){
            makeConst(obj[key])
        }
    })
}
var obj = {a:1.b:2};
makeConst(obj);
obj.a = 200;
obj.c = 100;
console.log(obj); // The value remains the sameCopy the code

summary

The keyword Variable ascension Block-level scope The initial value Change the value Call through window
let x Square root Yes No
const x Square root Yes No No
var Square root x Yes Yes

Deconstruction assignment

We often encounter a scenario where we take the value of an attribute from an object and store it in a variable.

Such as:

// Here item is an object {} that contains attributes name and age
let name = item.name; 
let age = item.age;Copy the code

In addition, such as ajax request callback functions

$.ajax({
    // Omit other arguments
    success:function(result){
        // Result is an object with code attributes and data attributes
        if(result.code === 200) {let data = result.data;
            data.forEach(){
​
            }
        }
    }
})Copy the code

ES6 provides a more convenient way to extract property values from objects, which deconstructs assignments.

define

ES 6 allows extracting values from arrays and objects and assigning values to variables in a pattern called Destructuring.

It has two actions:

- Deconstruction: Breaking structured data into individual values - Assignment: Storing deconstructed values in variablesCopy the code

Basic example

let arr = [1.2.3.4];
// Quickly fetch values from the array and assign them to variables A,b,c,d
let a = arr[0];
let c = arr[1];
console.log(a,b,c,d)Copy the code

Destruct assignment of arrays

It can quickly retrieve values from arrays and store them in variables. It’s essentially assigning values to variables.

Content:

  • Syntax and deconstruction rules

  • General use: The number of variables equals the length of the number

  • Unconventional use

    • Number of variables greater than array length

    • The number of variables is less than the array length

  • Use advanced

    • Skip unwanted values with null

    • The residual value

    • Complex nested scenarios

  • Small interview questions

Syntax and deconstruction rules

format

let[variable 1= default 1, variable 2= default 2, omit others, variable n== default n] = [array element 1, array element 2, omit others, array element n]Copy the code

The default value is optional and can be set or not set.

Rules:

  • The left and right sides of the assignment symbol are arrays. Take the right array from smallest to largest by index and place it in the left array.

  • If the variable on the left is not assigned a value:

    • If there is a default value, use its default value.

    • There is no default value, its value is undefined

Basic example

// The simplest scenario: the number of variables is equal to the number of elements in the array
let arr = [5.9.10];
let [a, b, c] = arr;
console.log(a, b, c); // Output 5, 9, 10
// This is equivalent to:
let a = arr[0];
let b = arr[1];
let c = arr[2];Copy the code

Note:

  • The format of the left and right sides of the “=” must be the same.

practice

// Many variables, few values
let arr = [5.9.10];
let [a, b, c, d] = arr;
console.log(a, b, c, d); 
// 5 9 10 undefined/ / the default value
let arr = [5.9];
let [a, b, c, d=4] = arr;
console.log(a, b, c, d); 
// 5 9 undefined 4,// There are fewer variables and more values
let arr = [5.9.10.8.3.2];
let [a, b] = arr;
console.log(a, b); 
/ / 5 and 9// Skip unwanted values with null
let arr = [5.9.10.8.3.2];
let [, , a, , b] = arr; 
console.log(a, b); 
/ / 3// Complex scenes can be deconstructed as long as they conform to the pattern
let arr = ['zhangsan'.18['175cm'.'65kg']].let [, ,[a,b]]=arr
// How to set a to 175cm and b to 65kg
console.log(a, b); // 175cm 65kgCopy the code

The residual value

let arr = [5.9.10.8.3.2];
let [a, b, ...c] = arr; / /... C receives the rest of the values, and the resulting C is an array
console.log(a, b, c); 
/ / the result:
// a = 5, 
// b = 9, 
// c = [10, 8, 3, 2]Copy the code

Note:

  1. . Only for the last variable. This variable is an array. If the number of elements in the array is greater than the number of variables, it will store the extra parameters in the array.

A quick interview question

Swap the values of two variables?

var a = 1, b = 2;
// Write code to interchange a,b values
/ /??????let arr=[a,b]
Copy the code
let[b,a]=arr
console.info(a,b); // Request output 2, 1Copy the code

Object destructuring assignment

Function: Quickly retrieves a value from an object and stores it in a variable. It’s essentially assigning values to variables.

Use formatting and rules

Full format

let {"Attribute Name 1": variable name 1= default 1,"Attribute Name 2": variable name 2= default 2... } = {"Attribute Name 1": Attribute value 1,"Attribute Name 2": Attribute value 2... }Copy the code

Parsing rules:

  • The default value is optional. You can specify a default value or not.

  • If the property name on the right matches the property name on the left, the property value on the right is assigned to the variable name on the left.

  • If the match on the right is not true, check whether the default value is used. If there is a default value, use the default value. If there is no default value, use undefined.

Compact format

If the attribute name in the left object is the same as the variable name, the left side can be merged:

let{variable name 1= default 1, variable name 2= default 2} = {"Attribute Name 1": Attribute value 1,"Attribute Name 2": Attribute value 2... }Copy the code

Parsing rules:

If the “attribute name” on the right matches the variable name on the left, the attribute value on the right is assigned to the variable name on the left.

The basic use

Scenario 1, variable names are the same as attribute names

// Scenario 1 requires variable names to be the same as attribute names by default
let { name, age } = {age: 27.name: 'attribution'};
console.log(name, age); 
​
let {a, c} = {a: 'hello'.b: 'world'};
console.log(a, c); // hello, undefinedCopy the code

Note:

  • The format of the left and right sides of = is the same.

  • An object is an unordered collection of attributes, so order is irrelevant

Scenario 2, the variable is renamed

// In scenario 2, you can rename a variable by
let {b, name:a} = {name: 'Wang Yangming'};
console.log(b, a,name); Copy the code

The residual value

// Collect all other attributes
let obj = {name:'zs'.age:20.gender:'male'};
let{name, ... a} = obj;console.log(name, a);
/ / the result:
// name = zs
// a = {age: 20, gender: "male "};Copy the code

Extension of function

Js functions are first-class citizens

Es6 has expanded the functionality of functions and added many features. Following this section we will be able to use functions with more flexibility and elegance.

Parameter Default Value

When defining a function, we can set the default value for the parameter: we have a guaranteed value to use if the user does not fill in this value. This feature is a basic feature in many other programming languages and was not supported prior to ES6, so we needed some workarounds to implement it.

Understand the defaults

The default values of the parameters were covered earlier in the course; for example, in the xhr.open(type, URL, asynchronous or not) method, the third parameter defaults to true, indicating asynchronous Ajax.

The default value means:

  • If passed, use the value you passed

  • If not, some special, pre-defined value is used. This value is the default value.

The realization of the ES5

// Workarounds for setting default values for parameters in ES5
function open(type, url,isAsync) {
    if(isAsync === undefined){
        isAsync = true;
    }
    console.log(type, url, isAsync);
}
// The following two sentences are equivalent
open("get"."common/get");// 
open("get"."common/get".true);
open("get"."common/get".false);Copy the code

The above code takes advantage of a feature of a parameter: its default value is undefined if no value is assigned. The code works, but is cumbersome, and ES6 provides a simpler implementation.

The realization of the ES6

format
functionFunction name (parameter name 1='Default value 1', parameter name 2='Default value 2', parameter name 3='Default value 3'){
    
}Copy the code
The sample
function open(type, url,isAsync=true) {
    console.log(type, url, isAsync);
}
// The following two sentences are equivalent
open("get"."common/get");// 
open("get"."common/get".true);
​
open("get"."common/get".false); 
​Copy the code

Think: can I skip isAsync, URL, and just set the default value for type?

Note:

  • Parameters with default values are placed at the far right of the parameter list.

Rest parameters

The rest (other, residual) argument is used to get the extra parameters of the function and put them in an array.

Syntax format

When defining a function, prefix the last argument with… , this parameter is the residual parameter;

let fn = function(Parameter 1, parameter 2... The rest parameters) {}letFn = (parameter 1, parameter 2... Rest parameters)=>{}Copy the code

The difference is made in the parameter list when a function is defined, but not when a function is called.

Application – instead of arguments

Write a function that takes the sum of all the arguments;

Method 1: Arguments

Method 2: REST parameters

function getSum (){
    // Write your code here
    var sum = 0 ; 
    for(var i = 0; i < arguments.length; i++){
        console.info( arguemnts[i])
        sum += arguments[i]; }}Copy the code

If you define the function as an arrow function, you can no longer use the arguments object internally. At this point, we can use it

The rest argument, which can be used instead of arguments. The code is as follows:

// We can use the rest of the parameters
const  getSum = (. values) = > {
    var sum = 0 ; 
    for(var i = 0; i < values.length; i++){
        console.info( values[i]) sum += values[i]; }}/ / call
console.log(fn(6.1.100.9.10));Copy the code

In contrast to arguments, it is a true array and can use all array methods.

Arrow function

Learning the arrow function makes code simpler and more efficient; Can read code written by others;

let fn3 = x= > x * 2;Copy the code

What is an arrow function

ES6 allows you to define a function using arrow functions. As we learned earlier, there are two ways to define a function:

  1. Functional declaration

  2. Functional expression

Now there’s a new way:

3. Arrow function

format

letFunction name = (parameter1. Parameter n) =>{/ / the function body
}Copy the code

Define an arrow function

// 1
function fu1(x){
    return x * 2;
}
// 2
let fn2 = function (x) {
    return x * 2;
}
// 3. Arrow function
let fn3 = (x) = > {
    return x * 2;
}Copy the code

When you first see this arrow function, it looks strange. If starting from the format of the function expression, it can be obtained through the following 2 evolutionary steps.

  1. Move the function keyword between () and {}

  2. Rewrite function as =>

Note:

- '=>' is a whole, without Spaces - arrow functions differ only in definition, but in function call format, there is no difference.Copy the code

Simplify the writing

  • When the parameter has one and only one, the parentheses can be omitted

    let f = (x) = > {console.log(x)}
    // Can be simplified to:
    let f = x= > {console.log(x)}Copy the code
  • When the function body has only one statement, you can omit the curly braces.

    let f = x= > {console.log(x)}
    // Can be simplified to:
    let f = x= > console.log(x)Copy the code
  • When the function body has only one statement, which is a return statement, the return and braces can be omitted.

    let f = x= > {return x*2 }
    // Can be simplified to:
    let f = x= > x*2Copy the code

    Note that if the return value is an object, add ()

    let f = x= > {return {a:1}}// Can be simplified to:
    let f = x= > {a:1} / / an error
    let f = x= >({a:1})Copy the code

The difference between arrow functions and ordinary functions

  • No arguments internally

  • There is no this inside

  • Cannot be used as a constructor

Without the arguments
let fn = (a,b) = > {
    console.log(arguments); // Arguments are not defined
};
fn(1.2);Copy the code
The internal this object refers to the object at which it was defined, not to the object at which it was used.
var name = 'lisi'; // When testing, var must be used here, because variables declared with let cannot be called with window
let obj = {
    name: 'zhangsan'.f1 : (a)= > {
        console.log(this); / / the window object
        console.log(this.name); // lisi
    },
    f2 : function(){
        console.log(this); / / the window object
        console.log(this.name); // lisi}}; obj.f1();Copy the code
Arrow functions cannot be constructors
let Person = (a)= >{};let obj = new Person(); Person is not a constructor
Arrow functions do not have their own this, so they cannot be constructorsCopy the code

In javascript, functions are first-class citizens. They can be used as constructors in addition to the most basic refinement of code, and they can do a lot of things. The arrow function proposed in ES6 is subtracted from the function.

Extension of arrays

Array is very important in js object, it provides a lot of methods, such as: sort, push, pop, unshift, splice, concat, map, forEach, filter, some,… . As one of the main work content of the front end is to interact with the back end of data, and the carrier of data interaction is mostly array, so we have very high requirements for the operation of array.

There was an interview question: Write down 10 array-related methods you’ve used.

This section will help us learn more about array methods.

Extended operator

What it does: Unpack the elements of an array: break an array into individual elements.

Format:… An array of

Basic usage

console.info(... [1, 2, 3]);Copy the code

Application 1: Array copy

Application 2: Array merging

Take all the values out of one array and put them in another array

var arr0 = ['a'.'b'];
var arr1 = [1.2.3];
var arr2 = [4. arr1];var arr3 = [..arr0 ,...arr1];Copy the code

Application 3: math.max ()

Math.max(1.3.4.6);
var arr = [1.3.4.6];
Math.max(... arr);/ / or Math. Max. Apply (this,,2,3,566 [1])Copy the code

Array.from()

Function: Convert non-array objects into arrays.

Format: Array = array. from(non-array object)

Its arguments have three cases:

  1. Custom, specially formatted objects.

let fakeArr = {
  0: 'a'.1: 'b'.2: 'c'.length: 3
};Copy the code

It’s for demonstration purposes, not for practical use.

  1. The arguments object

  2. The collection of Nodelists returned by DOM operations

The find method

In real development, we often encounter a scenario where we find elements in an array that match the criteria. The focus of our discussion will be on finding qualifying elements from arrays. Of course, we can do this by writing a loop, but es6 now provides this functionality. find/findIndex

Finds the first element (or subscript) in the array that matches our criteria.

format

Find and findIndex are in the same format.

let result = [].find(function(item,index,self){ 
    //.... 
    // If the search criteria are met
    return true;
})Copy the code
  • The callback takes three arguments: the value of an array element, the index, and the entire array

  • If a loop returns true, the find and findIndex methods return the first element or index that satisfies this condition

Execute the process

  • The find and findIndex methods iterate over the array passed in

  • If at some point in the callback, the result of the search is returned, and the value is the element (or subscript) in the loop. If no return true is found, undefined is returned.

  • FindIndex finds the first member of the array that meets the criteria and returns the index of that member, or -1 if not found.

A simple example

// Usage: find the first number in the array that is less than 0
let arr = [1.2.4.0.4 -.3.2 -.9];
let result = arr.find(function (item) {
    return item < 0; // During traversal, search according to this condition
});
console.log(result); / / - 4Copy the code

Notice how the arrow functions simplify the code.

findIndex

FindIndex is used similarly to find, except that instead of looking for elements in an array, it looks for their subscripts.

includes()

Function: Checks whether an array contains a value, returning true/false

Format: array. includes(parameter 1, parameter 2)

  • Parameter 1, must, indicates what to look for

  • Argument 2, optional, indicates where to start the search, and 0 indicates starting from the first element. The default value is 0.

Example:

let arr = [1.4.3.9];
console.log(arr.includes(4)); // true
console.log(arr.includes(4.2)); // select * from 2; // select * from 2
console.log(arr.includes(5)); // falseCopy the code

Strings also have this method, and the function is similar.

The expansion of the String

There are new features for strings in ES6, and we’ll look at a few of them:

  • Template string

  • includes

  • startsWith

  • endWith

  • repeat

Template string

When doing string concatenation, using + to concatenate complex content is cumbersome, and template strings solve this problem.

Format: ‘${variable} ${expression}’

Grammar:

  • The template string uses backquotes around the content, similar to the “” of a regular string.

  • ${} acts as a delimiter, which can write variable names, expressions, and so on.

  • Allow string to be wrapped inside, code better read better experience

Example:

let name = 'zs';
let age = 18;
// Concatenate multiple variables, using placeholders in template strings to make it easier to understand
let str = I was `${name}This year,${age}`;
​
// Too much content can be wrapped directly
let obj = [{name: 'flex'.age: 20}, {name: 'james'.age: 21}];
​
let arr = ['175cm'.'60kg'];
let html = `
    <div>
        <ul>
            <li>${obj.name}</li>
            <li>${obj.age}</li>
            <li>${arr[0]}</li>
            <li>${arr[1]}</li>
        </ul>
    </div>Copy the code

includes()

  • Format: str.includes(searchString, [position])

  • Function: Returns a Boolean value indicating whether the parameter string was found

    • Position: Search for substrings at the index position of the current string. The default value is 0.

startsWith()

  • Format: str.startswidth (searchString, [position])

  • Function: Returns a Boolean value indicating whether the argument string is at the head of the original string or at the specified position

    • Position: Searches the beginning of the searchString in STR. The default value is 0, which is the beginning of the actual string.

endsWith()

  • Format: str.endswith (searchString, [len])

  • Function: Returns a Boolean value indicating whether the argument string is at the end of the original string or at a specified position.

    • Len: optional. As the length of STR. The default value is str.length.

repeat()

The repeat method returns a new string, repeating the original string n times.

Grammar: STR. Repeat (n)

let html = '<li>itheima</li>';
html = html.repeat(10);Copy the code

The Set object

Set means Set. Is a new built-in object in ES6. It is similar to an array, but the values of its members are unique, that is, there are no duplicate values. It makes it very easy to use it to do array de-duplication.

Create a set object

  • Create an empty set;

  • Create a set from an existing array

// 1. Basic usage
let set = new Set(a);// Get an empty Set objectlet set = new Set([1.2.3])Copy the code

The member method of Set

  • Size: property that gets the number of members in a set, equivalent to the length in an array

  • Add (value) : Adds a value and returns the Set structure itself.

  • Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful.

  • Has (value) : Returns a Boolean value indicating whether the value is a member of Set.

  • Clear () : Clears all members with no return value.

  • The forEach: traversal

Application – Array deduplication

let arr = [1.1.2.3.3];
console.info([...new Set(arr)])Copy the code

4. A concise way to define objects

  • Simplification of attribute names

  • Simplification of the method

let name = 'zhangsan', age = 20, gender = 'woman';
let obj = {
    name: name, // The original way of writing
    age, // The property of the object is the same as the name of the variable
    gender,
    fn1:function(){  //
        console.log(123);
    },
    fn2 () { // Can be omitted
        console.log(456); }};console.log(obj.age); / / 20
obj.fn2(); / / 456Copy the code

ECMAScript 6 degradation processing

ES 6 compatibility issues

  • ES6 (October 2015) is good, but there are compatibility issues, ie7-IE11 basically does not support ES6

    ES6 compatibility list

  • ES6 is supported in modern browsers, mobile devices, and Node.js

  • We’ll talk later about how to handle ES6 compatibility

ES 6 degradation processing

Because ES6 has browser compatibility issues, you can use tools to degrade (convert ES6 code to ES5 code), such as Babel

Babel’s website] (www.babeljs.cn/)

Real-time transcoding: babeljs. IO /repl