"Introduction to ECMAScript 6" [Second, Destructuring and Assignment of Variables] (Continuous Update ...)

This series is aimed at simplifying Ruan Yifeng's article, making it easier for everyone to learn to read

Foreword:

Let's take a look at es6's new syntax deconstruction , which is similar to pattern matching.

First, the destructuring assignment of the array

For example, how to assign values ​​to multiple variables:

var a =1;
var b =2;
var c =3;

Need to write multiple variables is particularly troublesome, we first use the previous simplified method.

var a=1,b=2,c=3;

Now that es6 introduces destructuring, we can use destructuring assignment of arrays to make assignment easier.

1. Complete deconstruction

let [a,b,c]=[1,2,3];

You can extract values ​​from the array and assign values ​​to the variables according to the corresponding positions. In essence, this writing is "pattern matching", as long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value.
Next, we give a few more examples:

// 1、一一对应
let [,,v]=[,,1];
console.log(v) // 1
// 2、可以利用扩展符合并数组项
let [a,...b]=[1,2,3];
console.log(a) // 1
console.log(b) //[2,3]
// 3、如果左边不能一一对应右边的话,使用扩展符并且位置在末尾时,打印的为空数组,c没有对应,则是undefined;
let [a,c,...b]=[1];
console.log(a); // 1
console.log(b); // []
console.log(c); // undefined
// 4、如果没有一一对应的情况下,扩展符在中间,就会出错 `let [a,...b,d,c]=[1];`这种情况也一样
let [a,...b,c]=[1];
// Uncaught SyntaxError: Rest element must be last element

If the destructuring is unsuccessful, the value of the variable is equal to undefined. In the fourth case, if we put ...bthe position in the middle, we will make an error, and at the end we just print an empty array.

Let us give a few more practical examples, such as exchange value. Previously the exchange value had to be declared to define a variable, like this.

var a = 10;
var b = 20;
var temp = a;
a = b;
b = temp; 

It seems that it is more circumvent and the code is longer. Now we use es6 deconstruction, it can be like this.

let a = 10;
let b = 20;
[a,b] = [b,a];

2. Incomplete structure

Next, let's look at the next special example, called incomplete deconstruction. Is the pattern to the left of the equal sign, matching only part of the array to the right of the equal sign

let [x, y] = [1, 2, 3];
x // 1
y // 2

let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4

3. The default value

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

Summary: The elements of the array are arranged in order, and the value of the variable is determined by its position.

Second, the object's destructuring assignment

Destructuring can be used not only for arrays, but also for objects. like this.

 let { a, b } = { a: '1', b: '2' };
   console.log(a); // '1'
   console.log(b); // '2'

There is no order for the attributes of the object, and the variable must have the same name as the attribute to get the correct value.
Otherwise it will pop upundefined

  let { a, c } = { a: '1', b: '2' };
   console.log(c); // undefined

If you have to output cit, you must write it like this:

   let { a, b:c } = { a: '1', b: '2' };
   console.log(c); // 2

What the pattern matches here bis that the variable is actually assigned c.

Here we talk about a practical example, which is to assign the method of an existing object to a variable.

// 数学对象中的几个方法
let { log, sin, cos } = Math;

// 这里必须是log。不能是log1或者其他的变量,因为log是console的一个方法。
const { log } = console;
log('hello') // hello

One more example.

// 获取到的数据
let jsonData = {
id: 1,
status: "OK",
data: [1, 2]
};

let { id, status, data: number } = jsonData;
console.log(id, status, data); // 1,“OK”,[1,2]

Object destructuring can also specify default values.

var {x: y = 3} = {x: 5};
console.log(y) // 5
var {x: y = 3} = {};
console.log(y) // 3

Third, the destructuring assignment of the string

const [a, b, c, d, e] = 'hello';
console.log(a); // "h"
console.log(b); // "e"
let {length : x} = 'hello'; // 我们可以使用字符串自带的length属性,来获取值。
console.log(x) // 5

Conclusion:

Finally, we will talk about two practical examples based on the characteristics of the array and the object itself:
1.

// 返回数组
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

2、

// 参数是一组有次序的值,利用数组的解构赋值。
function f([x, y, z]) { ... }
f([1, 2, 3]);

// 参数是一组无次序的值,利用对象的解构赋值。
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

Thank you for browsing! Welcome to the next chapter. We work hard together on the front end

Published 172 original articles · praised 865 · 2.02 million views

Guess you like

Origin blog.csdn.net/qq_39045645/article/details/103786169