Home Web Front-end JS Tutorial Detailed explanation of destructuring assignment of ECMAScript6 variables

Detailed explanation of destructuring assignment of ECMAScript6 variables

Feb 08, 2018 pm 01:07 PM
Assignment

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 // []
Copy after login

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];
Copy after login

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
Copy after login

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] = {};
Copy after login

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;
Copy after login

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"
Copy after login

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
Copy after login

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'
Copy after login

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
Copy after login

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];
}
Copy after login

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
Copy after login

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"
Copy after login

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
Copy after login

In fact, the destructuring assignment of the object is the abbreviation of the following form

var { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };
Copy after login

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
Copy after login

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"
Copy after login

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}); // 成功
Copy after login

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"
Copy after login

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
Copy after login

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]
Copy after login

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"
Copy after login

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
Copy after login

If the destructuring fails, the value of the variable is equal to undefined

var {foo} = {bar: 'baz'};
foo // undefined
Copy after login

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'};
Copy after login

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});
Copy after login

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;
Copy after login

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"
Copy after login

Array-like objects have a length attribute, so this attribute can also be deconstructed and assigned

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

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
Copy after login

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
Copy after login

Destructuring assignment of function parameters

function add([x, y]){
  return x + y;
}
add([1, 2]); // 3
Copy after login

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]
Copy after login

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]
Copy after login

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 } };
Copy after login

2.函数参数中不能使用圆括号

// 报错
function f([(z)]) { return z; }
Copy after login

3.赋值语句中,不能将整个模式,或嵌

套模式中的一层,放在圆括号之中

将整个模式放在模式之中,导致报错

// 全部报错
({ p: a }) = { p: 42 };
([a]) = [5];
Copy after login

将嵌套模式的一层,放在圆括号之中,导致报错

[({ p: a }), { x: c }] = [{}, {}];
Copy after login

可以使用圆括号的况

赋值语句的非模式部分,可以使用圆括号

[(b)] = [3]; // 正确
({ p: (d) } = {}); // 正确
[(parseInt.prop)] = [3]; // 正确
Copy after login

首先它们都是赋值语句,而不是声明语句;其次它们的圆括号都不属于模式的一部分。第一行语句中,模式是取数组的第一个成员,跟圆括号无关;第二行语句中,模式是p,而不是d;第三行语句与第一行语句的性
质一致

用途

1.交换变量的值

[x, y] = [y, x];
Copy after login

2.从函数返回多个值

// 返回一个数组
function example() {
  return [1, 2, 3];
}
var [a, b, c] = example();
// 返回一个对象
function example() {
  return {
   foo: 1,
   bar: 2
  };
}
var { foo, bar } = example();
Copy after login

3.函数参数的定义

解构赋值可以方便地将一组参数与变量名对应起来

function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
Copy after login

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]
Copy after login

5.函数参数的默认值

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

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) {
// ...
}
Copy after login

7.输入模块的指定方法

const { SourceMapConsumer, SourceNode } = require("source-map")
Copy after login

相关推荐:

ECMAScript6是什么?

ECMAScript6入门之Class对象的实例详解

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable copy and paste for VMware virtual machines How to enable copy and paste for VMware virtual machines Feb 21, 2024 am 10:09 AM

You can easily copy and paste text and files between VMware virtual machines (VMs) and physical systems. This capability allows you to easily transfer images, formatted and unformatted text, and even email attachments between virtual machines and host systems. This article will show you how to enable this feature and demonstrate methods for copying data, files, and folders. How to Enable Copy/Paste in VMware VMware provides three different ways to copy data, files or folders from a virtual machine to a physical computer and vice versa, as explained below: Copy and Paste Elements Drag and Drop Feature Folder Sharing 1 ] Enable copy-paste using VMware Tools You can use the keyboard if your VMWare installation and guest operating system meet the requirements

How to copy a page in Word How to copy a page in Word Feb 20, 2024 am 10:09 AM

Want to copy a page in Microsoft Word and keep the formatting intact? This is a smart idea because duplicating pages in Word can be a useful time-saving technique when you want to create multiple copies of a specific document layout or format. This guide will walk you through the step-by-step process of copying pages in Word, whether you are creating a template or copying a specific page in a document. These simple instructions are designed to help you easily recreate your page without having to start from scratch. Why copy pages in Microsoft Word? There are several reasons why copying pages in Word is very beneficial: When you have a document with a specific layout or format that you want to copy. Unlike recreating the entire page from scratch

Disable or enable automatic copy selection for copying in Terminal Disable or enable automatic copy selection for copying in Terminal Mar 24, 2024 am 09:46 AM

This article will show you how to enable or disable automatic copying of selections to the clipboard in Windows Terminal. Windows Terminal is a multi-tab terminal emulator developed by Microsoft specifically for Windows 11/10, replacing the traditional command prompt. It supports running applications such as Command Prompt, PowerShell, WSL, Azure, etc. Often when working in the terminal, users need to copy commands and output, however the terminal does not support copying selection operations by default. Keep reading this article to learn how to fix this issue. How to enable or disable automatic copying of selections to cache in Terminal? Here's how you can enable or disable automatic copying of selections to the Terminal clipboard: Open the Terminal application and click above

Unlock macOS clipboard history, efficient copy and paste techniques Unlock macOS clipboard history, efficient copy and paste techniques Feb 19, 2024 pm 01:18 PM

On Mac, it's common to need to copy and paste content between different documents. The macOS clipboard only retains the last copied item, which limits our work efficiency. Fortunately, there are some third-party applications that can help us view and manage our clipboard history easily. How to View Clipboard Contents in Finder There is a built-in clipboard viewer in Finder, allowing you to view the contents of the current clipboard at any time to avoid pasting errors. The operation is very simple: open the Finder, click the Edit menu, and then select Show Clipboard. Although the function of viewing the contents of the clipboard in the Finder is small, there are a few points to note: the clipboard viewer in the Finder can only display the contents and cannot edit them. If you copied

What are the assignment methods in php? What are the assignment methods in php? Jul 26, 2023 pm 01:11 PM

The assignment methods in PHP include: 1. Direct assignment, use the "=" operator to directly assign a value to a variable; 2. Reference assignment, use the "=&" operator to assign a reference to a variable to another variable; 3. Dynamic assignment , using variable variables to assign values ​​through the string form of variable names; 4. Array assignment, assigning an array to another variable; 5. List assignment, assigning the value of an array to a set of variables, and multiple assignments can be made at one time value; 6. Object assignment, assign an object to a variable; 7. Use the extended form of the assignment operator, such as +=, -=, etc.

Learn variable definition and assignment in Golang Learn variable definition and assignment in Golang Jan 18, 2024 am 10:00 AM

The definition and assignment of variables in Golang require specific code examples. In Golang, the definition and assignment of variables are very simple and intuitive. This article will introduce the definition and assignment of variables in Golang through specific code examples. First, let's take a look at the definition of variables in Golang. In Golang, the definition of variables can be done using the var keyword. The specific syntax is as follows: var variable name type. Among them, var represents the definition keyword of the variable, and the variable name is the variable you define.

Tips and Notes: Different String Array Assignment Methods Tips and Notes: Different String Array Assignment Methods Dec 26, 2023 am 11:30 AM

Introduction to tips and precautions for using different ways to assign values ​​to string arrays: In programming, it is often necessary to use arrays to store a set of related data. Especially when dealing with strings, it is often necessary to use string arrays to store multiple strings. This article will introduce some common methods, tips and precautions for assigning values ​​to string arrays, and provide code examples. Direct assignment Direct assignment is the simplest way. You can directly assign values ​​to the array elements while declaring the string array. The sample code is as follows: String[]fruit

What are the methods of assigning values ​​to string arrays? What are the methods of assigning values ​​to string arrays? Dec 25, 2023 pm 05:07 PM

The assignment methods of string arrays in common programming languages: 1. Python: "string_array = ["apple", "banana", "cherry"]"; 2. Java: "String[] stringArray = {"apple", "banana" ", "cherry"}"; 3. C++ and so on.

See all articles