ES6 allows extracting values from arrays and objects and assigning values to variables according to certain patterns. This is called destructuring. This article mainly shares with you examples of destructuring nested arrays. Let’s take a look at var [ a, b, c] = [1, 2, 3];
This way of writing 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.
The following are some examples of using nested arrays for destructuring
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 // []
If the destructuring is unsuccessful, the value of the variable will be equal to undefined
The value of foo will be equal to undefined
var [foo] = []; var [bar, foo] = [1];
Incomplete deconstruction means that the pattern on the left side of the equal sign only matches part of the array on the right side 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
If the right side of the equal sign is not an array, an error will be reported.
// 报错let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};
Destructuring assignment is not only applicable to the var command, but also to the let and const commands
var [v1, v2, ..., vN ] = array; let [v1, v2, ..., vN ] = array; const [v1, v2, ..., vN ] = array;
For the Set structure, the destructuring assignment of the array can also be used.
let [x, y, z] = new Set(["a", "b", "c"]); x // "a"
As long as a certain data structure has an Iterator interface, destructuring assignment in the form of an array can be used.
function* fibs() { var a = 0; var b = 1; while (true) { yield a; [a, b] = [b, a + b]; } } var [first, second, third, fourth, fifth, sixth] = fibs(); sixth // 5
fibs is a Generator function that natively has an Iterator interface. Destructuring assignment will obtain the value from this interface in turn
Destructuring assignment allows specifying a default value.
var [foo = true] = []; foo // true [x, y = 'b'] = ['a']; // x='a', y='b' [x, y = 'b'] = ['a', undefined]; // x='a', y='b'
ES6 internally uses the strict equality operator ( === ) to determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined , the default value will not take effect.
var [x = 1] = [undefined]; x // 1 var [x = 1] = [null]; x // null
If an array member is null, the default value will not take effect, because null is not strictly equal to undefined
function f() { console.log('aaa'); } let [x = f()] = [1]; //等价于 let x; if ([1][0] === undefined) { x = f(); } else { x = [1][0]; }
If the default value is an expression, then the expression is lazily evaluated , that is, it will only be evaluated when used
The default value can refer to other variables of destructuring assignment, but the variable must have been declared
let [x = 1, y = x] = []; // x=1; y=1 let [x = 1, y = x] = [2]; // x=2; y=2 let [x = 1, y = x] = [1, 2]; // x=1; y=2 let [x = y, y = 1] = []; // ReferenceError
because x uses the default value When y, y has not been declared
Destructuring assignment of objects
var { foo, bar } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb"
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 are not in order, The variable must have the same name as the attribute to get the correct value
var { bar, foo } = { foo: "aaa", bar: "bbb" }; foo // "aaa" bar // "bbb" var { baz } = { foo: "aaa", bar: "bbb" }; baz // undefined
In fact, the destructuring assignment of the object is the abbreviation of the following form
var { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
The internal mechanism of the destructuring assignment of the object is to first find the same name attributes, and then assign them to the corresponding variables. What is actually assigned is the latter, not the former
var { foo: baz } = { foo: "aaa", bar: "bbb" }; baz // "aaa" foo // error: foo is not defined
In the above code, what is really assigned is the variable baz, not the mode foo
The declaration and assignment of the variable are integrated. For let and const, variables cannot be redeclared, so once the assigned variable has been previously declared
, an error will be reported
let foo; let {foo} = {foo: 1}; // SyntaxError: Duplicate declaration "foo" let baz; let {bar: baz} = {bar: 1}; // SyntaxError: Duplicate declaration "baz"
Because the var command allows redeclaration, this error will only occur when using let and const Appears with const command. If there is no second let command, the above code will not report an error
let foo; ({foo} = {foo: 1}); // 成功 let baz; ({bar: baz} = {bar: 1}); // 成功
Like arrays, destructuring can also be used for objects with nested structures
var obj = { p: [ "Hello", { y: "World" } ] }; var { p: [x, { y }] } = obj; x // "Hello" y // "World"
At this time, p is the pattern, not Variables, therefore will not be assigned
var node = { loc: { start: { line: 1, column: 5 } } }; var { loc: { start: { line }} } = node; line // 1 loc // error: loc is undefined start // error: start is undefined
Only line is a variable, loc and start are both patterns, and will not be assigned
Example of nested assignment.
let obj = {}; let arr = []; ({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true }); obj // {prop:123} arr // [true]
The destructuring of the object also specifies the default value
var {x = 3} = {}; x // 3 var {x, y = 5} = {x: 1}; x // 1 y // 5 var { message: msg = "Something went wrong" } = {}; msg // "Something went wrong"
The condition for the default value to take effect is that the attribute value of the object is strictly equal to undefined
var {x = 3} = {x: undefined}; x // 3 var {x = 3} = {x: null}; x // null
If the destructuring fails, the value of the variable is equal to undefined
var {foo} = {bar: 'baz'}; foo // undefined
The destructuring mode is a nested object, and the parent property of the child object does not exist, then an error will be reported
// 报错 var {foo: {bar}} = {baz: 'baz'};
The foo property of the object on the left side of the equal sign corresponds to a child object. The bar attribute of this sub-object will report an error when destructuring. Because foo is equal to undefined at this time, an error will be reported if you take the sub-property again
If you want to use a declared variable for destructuring assignment, you must be very careful
// 错误的写法 var x; {x} = {x: 1}; // SyntaxError: syntax error // 正确的写法 ({x} = {x: 1});
Because the JavaScript engine will interpret {x} understood as a block of code, resulting in a syntax error. This problem can be solved only by not writing the curly braces at the beginning of the line to prevent JavaScript from interpreting them as code blocks.
Destructuring assignment of objects can easily assign methods of existing objects to a variable
let { log, sin, cos } = Math;
Assign the logarithm, sine, and cosine methods of the Math object to the corresponding variables, which will be much more convenient to use.
Destructuring and assigning values to strings
Strings can also be destructured and assigned. At this time 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 have a length attribute, so this attribute can also be deconstructed and assigned
let {length : len} = 'hello'; len // 5
Numeric and Boolean values Destructuring assignment
When destructuring assignment, if the right side of the equal sign is a numerical value or a Boolean value, it will be converted into an object first
let {toString: s} = 123; s === Number.prototype.toString // true let {toString: s} = true; s === Boolean.prototype.toString // true
The packaging objects of numerical values and Boolean values have the toString attribute, so the variable s You can get the value
The rule of destructuring assignment is that as long as the value on the right side of the equal sign is not an object, convert it to an object first. Since undefined and null cannot be converted into objects, destructuring and assigning them will result in an error.
let { prop: x } = undefined; // TypeError let { prop: y } = null; // TypeError
Destructuring assignment of function parameters
function add([x, y]){ return x + y; } add([1, 2]); // 3
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]
The parameter of function move is an object. By destructuring this object, Get the values of variables x and y. If the destructuring fails, x and y are equal to the default values
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]
is to specify default values for the parameters of function move instead of specifying default values for variables x and y, so you will get different results from the previous way of writing. undefined will trigger the default value of the function parameter
Parentheses problem
解构赋值虽然很方便,但是解析起来并不容易。对于编译器来说,一个式子到底是模式,还是表达式,没有办法从一开始就知道,必须解析到(或解析不到)等号才能知道如果模式中出现圆括号怎么处理。ES6的规则是,只要有可能导致解构的歧义,就不得使用圆括号。但是,这条规则实际上不那么容易辨别,处理起来相当麻烦。因此,建议只要有可能,就不要在模式中放置圆括号
不能使用圆括号的情况
1.变量声明语句中,不能带有圆括号
// 全部报错 var [(a)] = [1]; var {x: (c)} = {}; var ({x: c}) = {}; var {(x: c)} = {}; var {(x): c} = {};} var { o: ({ p: p }) } = { o: { p: 2 } };
2.函数参数中不能使用圆括号
// 报错 function f([(z)]) { return z; }
3.赋值语句中,不能将整个模式,或嵌
套模式中的一层,放在圆括号之中
将整个模式放在模式之中,导致报错
// 全部报错 ({ p: a }) = { p: 42 }; ([a]) = [5];
将嵌套模式的一层,放在圆括号之中,导致报错
[({ p: a }), { x: c }] = [{}, {}];
可以使用圆括号的况
赋值语句的非模式部分,可以使用圆括号
[(b)] = [3]; // 正确 ({ p: (d) } = {}); // 正确 [(parseInt.prop)] = [3]; // 正确
首先它们都是赋值语句,而不是声明语句;其次它们的圆括号都不属于模式的一部分。第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性
质一致
用途
1.交换变量的值
[x, y] = [y, x];
2.从函数返回多个值
// 返回一个数组 function example() { return [1, 2, 3]; } var [a, b, c] = example(); // 返回一个对象 function example() { return { foo: 1, bar: 2 }; } var { foo, bar } = example();
3.函数参数的定义
解构赋值可以方便地将一组参数与变量名对应起来
function f([x, y, z]) { ... } f([1, 2, 3]); // 参数是一组无次序的值 function f({x, y, z}) { ... } f({z: 3, y: 2, x: 1});
4.提取JSON数据
var jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]
5.函数参数的默认值
jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, global = true, // ... more config }) { // ... do stuff };
6.便利Map结构
var 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 // 获取键名 for (let [key] of map) { // ... } // 获取键值 for (let [,value] of map) { // ... }
7.输入模块的指定方法
const { SourceMapConsumer, SourceNode } = require("source-map")
相关推荐:
ECMAScript6新增值比较函数Object.is_javascript技巧
The above is the detailed content of Detailed explanation of destructuring assignment of ECMAScript6 variables. For more information, please follow other related articles on the PHP Chinese website!