ES6 learning one (variable declaration and structure assignment)

1. Variable declaration

ES6 has a total of 6 ways to declare variables, namely var, function, let, const, import, class. varThere is no difference between the command and functiones5. Today we mainly record letand constcommand ( I haven’t understood the command carefully, importand classI will add it later).


1.1 let command

Function : Declare a variable, but the declared variable is intended to be valid in the block-level scope where the let command is located, and there is no variable promotion.

// 只声明
let a
// 声明时赋值
let b = 1
// 声明后赋值
let c
c=2

console.log(a); // undefined
console.log(b); // 1
console.log(c); // 2

1.2 const command

Function : Declare a constant, similar to the let command.

Initialization by assignment at declaration

Compared with the let command, once a constant is declared, its value cannot be changed, so it is necessary to assign and initialize the constant when it is declared.

// 只声明
const a // SyntaxError: Missing initializer in const declaration
console.log(a); // 不执行

Data of reference types such as objects and arrays

Because the addresses of these data save pointers to actual data, the content of these data can be modified.
But if you directly replace or reassign the entire object or array, its actual address will be changed and an error will be reported.

const aoo = {
    
    a: 1}

aoo.a = 2
aoo.b = 1

console.log(aoo); // { a: 2, b: 1 }


aoo = {
    
     c: 3 }

console.log(aoo); // 不执行

freeze object

To make an object immutable, you can useObject.freze()

const aoo = Object.freze({
    
    a: 1}) // TypeError: Object.freze is not a function

aoo.a = 2 // 以下不执行
aoo.b = 1

console.log(aoo);

1.3 Block-level scope

ES6 has added a block-level scope. As long as there is one {}, {}it represents a block-level scope. The variables used letand constdeclared are used in the current block-level scope.

No block-level scope causes inner variables to leak as global variables

In es5, there are only global scope and function scope (the scope opened by the function), so inner variables will be leaked as global variables (for example: loop)

var s = 'hello';

for (var i = 0; i < s.length; i++) {
    
    
  console.log(s[i]);
}

console.log(i); // 5

Because there is no block-level scope, the inner variables that are only used for loops iare leaked as global variables

let s = 'hello';

for (let i = 0; i < s.length; i++) {
    
    
  console.log(s[i]);
}

console.log(i); // ReferenceError: i is not defined

The block-level scope restricts the inner variable used as a loop ito only be in the scope, and the outer layer does not have ithis variable

Variables cannot be double-declared

In the same block-level scope, variables cannot be declared repeatedly, otherwise an error will be reported

let a
let a = 1 // SyntaxError: Identifier 'a' has already been declared

1.4 No Variable Boost and Temporary Deadband

Variable promotion In es5 or varwhen using commands, variables can be used before declaration, but the value is undefined.

There is a variable promotion that causes the inner variable to override the outer variable

var tmp = new Date();

function f() {
    
    
  console.log(tmp);
  if (false) {
    
    
    var tmp = 'hello world';
  }
}

f(); // undefined

Because the tmp declared in the variable promotion () overwrites the value of the outer tmp

let tmp = new Date();

function f() {
    
    
  console.log(tmp);
  if (false) {
    
    
    let tmp = 'hello world';
  }
}

f(); // 2021-08-18T18:20:32.471Z

Without variable promotion, the value of the outer tmp is still the obtained time

es6 uses letand constcommands do not allow variable promotion, and the variables they declare must be used after declaration (including typeof), otherwise an error will be reported.

console.log(s); // ReferenceError: Cannot access 's' before initialization
let s = 'hello';

This error prompt is a temporary dead zone.

temporary dead zone

The temporary dead zone is to form a closed scope when using the let and const commands. Before the variable declaration position is a "dead zone", the variable can only be used after the declaration position.

Note that when typeof is used, an undeclared variable will not report an error; a declared variable will report an error if it is used before the declaration

console.log(typeof a);  // undefined

console.log(typeof b);  // ReferenceError: Cannot access 'b' before initialization
let b = 'b'


2. Variable deconstruction, assignment, setting aliases

Deconstruction : ES6 allows extracting values ​​from arrays and objects and assigning values ​​to variables according to certain patterns.

In essence, this writing method belongs to pattern matching. As long as the patterns on both sides are the same, the variable on the left will be assigned the corresponding value

let [a, b] = [1, 2]

console.log(a); // 1
console.log(b); // 2

incomplete deconstruction

However, es6 does not require that the patterns on the left and right sides are exactly the same, so the pattern on the left side of the equal sign only matches a part of the pattern on the right side of the equal sign, and incomplete deconstruction will occur , that is, the partial deconstruction assignment that can match is successful; the partial deconstruction that does not match fails, and the variable The value is equal to undefined

let [a, [b,c],d] = ['1', '2', '3']

console.log(a); // 1
console.log(b); // 2
console.log(c); // undefined
console.log(d); // 3

?When the value of the array on the right side of the equal sign is a Number type, an error will be reported if the modes on both sides of the equal sign are different.

let [a, [b,c],d] = [1, 2, 3] // TypeError: undefined is not a function

console.log(a);  //以下不执行
console.log(b); 
console.log(c);
console.log(d);

2.1 Destructuring assignment of different types of data

Object Destructuring Assignment

The object is deconstructed according to the key value, and the key can be exchanged at will

let {
    
     b, a, c } = {
    
    a: 1,b:2}

console.log(a); // 1
console.log(b); // 2
console.log(c); // undefined

Array Destructuring Assignment

The array is deconstructed according to the order of one-to-one correspondence, and the positions cannot be exchanged at will. It can be imagined that the subscript of the array is the key value of the object, and the keys will be different if the order is different, so the positions cannot be exchanged at will.

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

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

However, arrays can also be destructured as special objects in the manner of objects

let {
    
     1: b, 0: a } = [1, 2]

console.log(a); // 1
console.log(b); // 2

String Destructuring Assignment

The string will be converted into an array-like object and destructured in the form of an array;

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

It can also be deconstructed as a special object in the form of an object

let {
    
     0:a, 1:b, 2:c, 3:d, 4:e } = 'hello'
console.log(a); // h
console.log(b); // e
console.log(c); // l
console.log(d); // l
console.log(e); // o

Destructuring assignments for numeric and boolean values

Numeric and boolean values ​​will be converted to their wrapper objects and destructured in an object way

let {
    
    toString: s} = 123;
s === Number.prototype.toString // true

let {
    
    toString: s} = true;
s === Boolean.prototype.toString // true

Destructuring assignment of undefined and null

The rule for destructuring assignments is that whenever the right-hand side is not an array or object or array-like object value, convert it to an object first. Since undefined and null cannot be converted into objects, they will report an error when deconstructing and assigning

// let { prop: x } = undefined; // TypeError: Cannot destructure property 'prop' of 'undefined' as it is undefined.
let {
    
     prop: y } = null; // TypeError: Cannot destructure property 'prop' of 'null' as it is null.

Destructuring assignment of function parameters

Function parameters can be destructured and assigned according to the above rules according to different data types

[{
    
    name: 'a'},{
    
    name: 'b'},{
    
    name: 'c'}].map(({
     
     name}) => name)

2.2 Default values

Sometimes, we want to have a default value when deconstructing, and use this default value when deconstructing fails or is indeed equal to undefined.
Because es6 internally uses the strict equality operator (===) to determine whether a position has a value, the default value will only take effect when it is strictly equal to undefined that fails to deconstruct.

let {
    
     a='01', b='02', c='03' } = {
    
    a: 1, b: 2}

console.log(a); // 1
console.log(b); // 2
console.log(c); // 03

null value

According to the rules, if the position represented by the null value has a value, the value is null, and the default value will not take effect.

let {
    
     a='01', b='02', c='03' } = {
    
    a: 1, b: 2, c: null}

console.log(a); // 1
console.log(b); // 2
console.log(c); // null

Default value references destructure other variables

The default value can refer to destructured other variables, but the variable must have been declared

let [x = 0, y = x] = []
console.log(x); // 0
console.log(y); // 0

x has been declared and assigned a value of 0 before y is declared, so y can use x as the default value

let [x = y, y = 0] = [] // ReferenceError: Cannot access 'y' before initialization
console.log(x); // 以下不执行
console.log(y);

x uses y as the default value before y is declared, because there is no variable promotion, so an error is reported


2.3 Aliases

If the variable name is different from the attribute name, then you need to set the variable name as an alias of the attribute name

let {
    
     message: msg } = {
    
     message:'123' }
console.log(msg); // 123
console.log(message); // ReferenceError: message is not defined

In fact, what I usually write let {foo} = {foo:123}is let {foo:foo} = {foo:123}the abbreviation of

When the internal mechanism of object deconstruction and assignment, first find the attribute with the same name, and then assign it to the corresponding variable. The latter is actually assigned, not the former.


2.4 Parentheses (haven't used it, don't know it very well, I will add it later)

use a declared variable for destructuring assignment

Cases where parentheses cannot be used

When parentheses can be used

Guess you like

Origin blog.csdn.net/BAtodl/article/details/119792451