001-es6 variable declaration, destructuring assignment, destructuring assignment main purpose

1. Basic grammar

1.1. Six ways to declare variables

See the address: http://es6.ruanyifeng.com/#docs/let

let: local variable, block-level scope, use error before declaration

var: global variable, use undefined before declaration

const:Declare a read-only constant. Once declared, the value of the constant cannot be changed. Only the memory address does not change. If it is an object, the value corresponding to the memory invariant attribute is variable.

function:

import:

class:

1.2, variable destructuring assignment

See the address: http://es6.ruanyifeng.com/#docs/destructuring

1.2.1. Array

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

let [ , , third] = ["foo", "bar", "baz"];
third // "baz"

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

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
let [foo] = [];  //foo undefined
let [bar, foo] = [1];//foo undefined

If the right-hand side of the equal sign is not an array (or, strictly speaking, a traversable structure, see chapter "Iterator"), an error will be reported.

Support Set

let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
function* fibs() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5

In the above code, it fibsis a Generator function (see the chapter "Generator Function"), which has an Iterator interface natively. Destructuring assignments in turn get values ​​from this interface.

Defaults

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

Note that ES6 internally uses the strict equality operator ( ===) to determine whether a position has a value. So, the default value will only take effect if an array member is strictly equal undefined.

If the default value is an expression, then the expression is lazily evaluated, that is, it is evaluated only when it is used.

function f() {
  console.log('aaa');
}

let [x = f()] = [1];

In the above code, because xthe value can be obtained, the function fwill not be executed at all. The above code is actually equivalent to the following code.

let x;
if ([1][0] === undefined) {
  x = f();
} else {
  x = [1][0];
}

1.2.2. Objects

Object destructuring differs from arrays in one important way. The elements of the array are arranged in order, and the value of the variable is determined by its position; while the properties of the object have no order, the variable must have the same name as the property to get the correct value.

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

If the variable name does not match the attribute name, it must be written as follows.

let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"

let obj = { first: 'hello', last: 'world' };
let { first: f, last: l } = obj;
f // 'hello'
l // 'world'

1.2.3. String

Strings can also be assigned destructuring. This is because at this point, the string is converted into an array-like object.

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

Array-like objects all have a lengthproperty, so you can also destruct this property to assign values.

let {length : len} = 'hello';
len // 5

1.2.4. Destructuring assignment of numeric and boolean values

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

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

In the above code, the wrapper objects for numeric and boolean values ​​have toStringproperties, so variables scan take values.

The rule of destructuring assignment is that as long as the value to the right of the equal sign is not an object or an array, convert it to an object first. Since undefinedand nullcannot be converted to objects, destructuring and assigning them will result in an error.

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

1.2.5. Destructuring assignment of function parameters

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

In the above code, addthe parameter of the function is ostensibly an array, but the moment the parameter is passed in, the array parameter is decomposed into the variable xsum y. For the code inside the function, the parameters they can perceive are the xsum y.

Below is another example.

[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]

Destructuring of function parameters can also use default values.

function move({x = 0, y = 0} = {}) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, 0]
move({}); // [0, 0]
move(); // [0, 0]

In the above code, the parameter of the function is an object, and the value of the variable sum is moveobtained by destructuring the object . If destructuring fails, the sum equals the default value.xyxy

Note that writing below will give different results.

function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

move({x: 3, y: 8}); // [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); // [0, 0]

The above code movespecifies default values ​​for the parameters of the function, not for variables xand variables y, so it will get different results from the previous writing method.

undefinedThe default value of the function parameter is triggered.

[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]

Destructuring assignment, while convenient, is not easy to parse. For the compiler, there is no way to know whether a formula is a pattern or an expression from the beginning, and it must be resolved (or not resolved) to know.

The question that arises from this is what to do if parentheses appear in the pattern. The ES6 rule is that parentheses must not be used whenever there is an ambiguity that could lead to destructuring.

However, this rule is actually not that easy to discern and is rather cumbersome to deal with. Therefore, it is recommended to not put parentheses in patterns whenever possible.

1.3, the main purpose

(1) Swap the value of the variable

let x = 1;
let y = 2;

[x, y] = [y, x];

(2) Return multiple values ​​from a function

Functions can only return one value. If you want to return multiple values, you can only return them in an array or object. With destructuring assignment, it is very convenient to get these values ​​out.

// return an array

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// return an object

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

(3) Definition of function parameters

Destructuring assignment makes it easy to map a set of parameters to variable names.

// argument is an ordered set of values 
​​function f([x, y, z]) { ... }
f([1, 2, 3]);

// argument is an unordered set of values 
​​function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

(4) Extract JSON data

Destructuring assignment is especially useful for extracting data from JSON objects.

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]

(5) Default values ​​of function parameters

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};

var foo = config.foo || 'default foo';Specifying the default value of the parameter avoids writing such a statement inside the function body .

(6) Traverse the Map structure

Any object that deploys the Iterator interface can be for...oftraversed with a loop. The Map structure natively supports the Iterator interface, and with the destructuring and assignment of variables, it is very convenient to obtain key names and key values.

const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');

for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

If you only want to get the key name, or just want to get the key value, you can write it as follows.

// Get the key name 
for (let [key] of map) {
   // ... 
}

// Get key value 
for (let [,value] of map) {
   // ... 
}

(7) How to specify the input module

When loading a module, it is often necessary to specify which methods are entered. Destructuring assignment makes the input statement very clear.

const { SourceMapConsumer, SourceNode } = require("source-map");

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325128974&siteId=291194637