ES6 in js

1. Introduction to ECMAcript6

ECMAScript6 is a generation standard of the js language, which was released in June 2015. This section will introduce the concept of ES6 and the use of the transcoder babel.

1.1 The concept of ECMAScript6

The relationship between ECMAScript and JavaScript is: the former is the specification of the latter, and the latter is an implementation of the former.

The relationship between ES6 and ECMAScript 2015: ES6 is not only a historical term, but also a general reference. It means the next-generation standard of JS after version 5.1, covering ES2015, ES2016, ES2017, etc., while ES2015 is the official name, specifically referring to the year Published official version of the language standard. The ES6 mentioned in this chapter generally refers to the ES2015 standard.

1.2 Use of ES6 transcoder babel

Babel is a widely used ES6 transcoder that converts ES6 code to ES5 code for execution in older browsers. The configuration steps are in ~~~.

2.let and const commands

2.1 let command

Used to declare variables. Its usage is similar to var, but the variable it declares is only valid within the code block where the let command is located.

Syntax: let variable name;

  1. The scope of the let command is limited to the current code block
  2. Variable scope declared using the let command will not be forwarded
  3. cannot declare the same variable in the same scope

2.2 const command

The const command is used to declare a read-only constant. Once declared, the value of a constant cannot be changed.

Syntax: const variable name;

Once the const command declares a constant, it must be initialized immediately and cannot be left for later assignment. Otherwise, an error will be reported.

The scope of const is the same as that of let, and it is only valid in the block-level scope where the declaration is located.

The constants declared by the const command do not support promotion, and can only be used after the declaration, just like the let command.

Similarly, constants declared by const, like let, cannot be declared repeatedly.

In fact, what the const command guarantees is not that the value of the constant cannot be changed, but that the memory address pointed to by the constant cannot be changed. For simple types of data (numeric, string, boolean), the value is stored at the memory address pointed to by the constant, so it is equivalent to a constant. But for reference data types (such as objects), the memory address pointed to by the constant only stores an object address, and const can only guarantee that the object address cannot be changed. As for whether the properties of the object itself are variable, it is completely out of control up.

3. Parse assignment

Destructuring assignment is an extension to the assignment operator. ES6 allows to extract values ​​from arrays and objects according to a certain pattern, and then assign values ​​to variables, which is called Destructuring. In terms of code writing, the writing method of destructuring assignment is more concise and easy to understand, and the language is clearer.

3.1 Array destructuring assignment

3.1.1 Basic use

let [a,b,c]=[1,2,3];
console.log(a,b,c);//1,2,3

        The above code indicates that values ​​can be extracted from the array and assigned to variables according to the corresponding positions. In essence, this writing method belongs to "pattern matching". As long as the patterns on both sides of the equal sign are the same, the variable on the left will be assigned the corresponding value. In addition to basic usage, array destructuring also supports the following destructuring assignment forms.

 3.1.2 Destructuring nested arrays

        Arrays can contain arrays, which is called nested arrays. In the following code, the variable array contains arrays. During the matching process, the variables will be assigned values ​​according to the corresponding positions. That is, the variable a is assigned the value 1, the variable b is assigned the value 2, and the variable c is assigned the value 3.

let [a,[[b],c]]=[1,[[2],3]];
console.log(a,b,c);//1,2,3

3.1.3 Incomplete Deconstruction

        During the normal destructuring assignment process, but when the variable array matches a part of the assigned array, the destructuring can still be successful. At this time, the first matched value will be assigned to the variable, and the redundant values ​​will be ignored.

        In code 1 below, when variables a and b are accepted, only 1 and 2 in the array value are matched, while 3 is not matched successfully. In code 2, variable a has a value of 1; variable b matches the first value in the nested array, which is 2; and variable c has a value of 4.

        If the left and right arrays lack variables or values, they can be destructured successfully. If the deconstruction is unsuccessful, the value of the variable is equal to undefined. In the following code 3, the value of variable a is 1, and the value of variable b is 3.

//代码1
let [a,b]=[1,2,3];
console.log(a,b);//1,2
//代码2
let [a,[b],c]=[1,[2,3],4];
console.log(a,b,c);//1,2,4
//代码3
let [a,,b]=[1,2,3];
console.log(a,b);//1,3

3.1.4 The remainder operator

        In destructuring assignment, when the number of variable values ​​cannot be known, the rest operator (...) can be used for pattern matching. Usually, the remainder operator is placed at the end of the variable array, as shown in the following code. When matching, variable a matches 1, and variable b adopts the remainder operator, then both 2 and 3 of the array value are stored under variable b, the returned result b is an array, and output b displays [2,3].

let [a,...b]=[1,2,3];
console.log(a,b);//1,[2,3]

3.1.5 Destructuring default values

        Destructuring assignment allows default values ​​to be specified. During the matching process, if no matching is successful, the variable value is the default value set in advance. In the following code, the variable y is set to the default value "b". When deconstructing, if no new value is matched, the output shows that the value of variable y is "b".

let [x,y="b"]=["a"];
console.log(x,y);//"a","b"

3.2 Object destructuring assignment

There is an important difference between the deconstruction of an object and the deconstruction of an array. The elements of an array are arranged in order, and the value of a variable is determined by its position. However, the properties of an object have no order. The variable must have the same name as the property to get the correct value. value.

//对象解构赋值的基本用法
let {a,b}={b:"y",a:"x"};
console.log(a,b);//x,y
let {abc}={def:"ghj"};
console.log(abc);//undefined
/*a,b两个变量的次序,与等号右边两个同名属性的次序不一致,但是对取值完全没有影响。
变量abc则没有对应的同名属性,导致取不到值,最后等于undefined*/

//为了解决对象解构赋值中变量名与属性名不一致的问题,
let {foo:x,bar:y}={foo:"ES6",bar:"hello"};
console.log(x,y);//ES6,hello
/**foo与bar是匹配的模式,x和y才是变量。真正被赋值的是变量x和y,而不是模式foo与bar。
 * 通过这种写法即可解决变量名和属性名不一致的问题,对象解构赋值和数组解构赋值相同,
 * 除基础用法外,支持如嵌套,不完全解构等形式,二者使用方法一致。*/

//解构嵌套对象
let obj={p:["hello",{c:"woeld"}]};
let {p:[z,{c}]}=obj;
console.log(z,c);//hello,world

//不完全解构
let obje={a,b,...rest}={a:10,b:20,c:30,d:40};
console.log(a,b,rest);//10,20,{c:30,d:40}

//解构默认值
let {q=10,m=5}={q:3};
console.log(q,m);//3,5
let {a:aa=10,b:bb=5}={a:3};
console.log(aa,bb)//3,5

3.3 String Destructuring Assignment

String destructuring assignment is to convert a string into an array-like object,

let [a,b,c,d,e]="hello";
console.log(a,b,c,d,e);//h,e,l,l,o

3.4 Function parameter destructuring assignment

function add([x,y]){
    console.log(x+y);//3
}
add([1,2]);

The parameter of the function add() is an array on the surface, but at the moment when the parameter value is passed in, the parameter of the array is decomposed into variables x and y. For the code inside the function, the resulting parameters are x and y. 

4. Function extension

4.1 Function parameter default value

function foo(x,y){
    y=y || "world";
    console.log(x,y);
}
foo("hello");//hello world
foo("hello","");//hello world

 The foo() function contains two parameters, namely x and y, where the default value is set for the parameter y, and the value of y when y is not assigned. The value of y defaults to "World".

Set the default value for the function parameter in ES6 way.

function foo(x,y="world"){
    console.log(x,y);
}
foo("hello");//hello world
foo("Hello","");//Hello

The default value of function parameters also has its limitations, as follows.

  • Parameter variables are declared by default and cannot be declared again with let or const commands.
  • When using parameter defaults, functions cannot have parameters with the same name.
  • The parameter default value must be placed at the end of the parameter. 

4.2 rest parameter and name attribute

The rest parameter is used to obtain redundant parameters, and the name attribute is used to obtain the function name.

4.3 Arrow functions

Syntax: (parameter1,,,parameterN) => {function declaration}

Differences from ordinary functions:

  1. does not bind this object
  2. does not bind the arguments object 

5. Extension of built-in objects

5.1 Expansion of strings

5.1.2 Template strings

let name="Bob",time="today";
document.write(`Hello ${name},how are you ${time}?`);

Use backticks (``) instead of double quotes and single quotes in ordinary strings, which can be used as ordinary strings, and can also be used to define multi-line strings. At the same time, template strings can also be used to embed variables, embed strings or call functions,

 5.1.3 New String Operation Methods

Common string manipulation methods added in ES6
method describe

includes(string):boolean

Indicates whether the parameter string was found

startsWith(string):boolean

Indicates whether the participating digital string is at the head of the original string

endsWith(string):boolean

Indicates whether the parameter string is at the end of the original string

repeat(number):string

Returns a new string, which means repeating the original string n times

padStart(number,string):string

for header completion

padEnd(number,string):string

for tail completion

trimStart():string

Eliminate the airbus at the head of the string

trimEnd():string

remove trailing spaces
let str = "hello ECMAScript";
console.log(str.includes("h"));//true
console.log(str.startsWith("h"));//true
console.log(str.endsWith("t"))//true
console.log(str.repeat(3))//hello ECMAScripthello ECMAScripthello ECMAScript
console.log(str.padStart(18,"a"));//aahello ECMAScript
console.log(str.padEnd(18,"z"));//hello ECMAScriptzz
console.log(str.trimStart());//消除字符串头部的空格
console.log(str.trimEnd());//消除字符串尾部的空格

5.2 Expansion of arrays

5.2.1 Spread operator

The spread operator, represented by three dots (...), converts an array into a comma-separated sequence.

Syntax: ...array 

5.2.2 Array.from() method

The from() method is used to convert an array object or traversable object into a real array. Among them, the array-like object must have a length property. If there is no length attribute, an empty array is converted.

Syntax: let list=Array.from(array-like);

5.2.3 Array traversal method

ES6 adds a method to traverse arrays
method describe
keys():iterator Iterating over keys
values():iterator Iterating over the key values
entries():iterator Iterating over key-value pairs
for(let [i,v] of ["张三","李四"].entries()){
    console.log(i,v);
}

5.3 Extension of objects

5.3.1 Concise notation for attributes

let name="小明";
let birth="2023/5/19";
const Person={
    name,
    birth,
    getInfo(){
        console.log(`我的名字是:${this.name},我出生时间是:${this.birth}`);
    }
}
Person.getInfo();//我的名字是:小明,我出生时间是:2023/5/19

5.3.2 Object Add Method

1. Object.is() method

console.log(Object.is(NaN,NaN));//true
console.log(Object.is({},{}));//false
console.log(Object.is(+0,-0));//false

2. Object.assign() method

Syntax: Object.assign(target,source_1,...);

The first parameter of this method is the target object, and the following parameters are the source object, which can contain multiple source objects, or define a new object to receive the target object.

5.3.3 Object traversal methods

ES6 object traversal method
method describe
keys():iterator Put back the key names of all traversable properties of the parameter object itself
values():iterator Returns the key values ​​of all traversable properties of the parameter object itself
entries():iterator Returns an array of key-value pairs of all traversable properties of the parameter object itself

6. Set and Map objects

6.1 Set object

The data structure of the Set object is similar to an array, but the values ​​of the members are all unique and there is no repeated value.

Common properties and methods of the Set object
Classification name describe
Attributes size The total number of members of the Set instance
operation method add(value) Add a value, return the Set structure itself
delete(value) Delete a value, return a Boolean value, indicating whether the deletion is successful
has(value) Returns a boolean indicating whether the value is a member of the Set
clear() Clear all members, no return value
traversal method keys() A iterator that returns key names
values() Returns an iterator for key values
entries() Returns an iterator for key-value pairs
forEach() Use the callback function to iterate over each member

6.2 Map object

The object (Object) of js is essentially a collection of key-value pairs (Hash structure), but traditionally only strings can be used as keys, which brings great limitations to its use. To solve this problem, ES6 provides the Map object. It is also a collection of key-value pairs, but the scope of its "key" is not limited to strings, and various types of values ​​() can be used as keys.

Common properties and methods of the Map object
Classification name describe
Attributes size The total number of members of the Map object
operation method set(key,value) Set the key value corresponding to the key name key to value, and return the entire Map structure
get(key) Read the key value corresponding to the key, if the key cannot be found, return undefined
has(key) Returns a Boolean value indicating whether a key is in the current Map object
delete(key) Delete a key, return true. If deletion fails, return false
clear() Clear all members, no return value
traversal method keys() A iterator that returns key names
values() Returns an iterator for key values
entries() Returns a iterator over all members

Summary of this chapter

The genius in people's eyes is extraordinary not because of superior talent, but because of continuous hard work. 10,000 hours of tempering is a necessary condition for anyone to become a world super master from ordinary people.

                                                                                        - Gladwell, "The Ten Thousand Hour Rule"

Guess you like

Origin blog.csdn.net/zouzxxi/article/details/130725393