Destructuring Assignment

JavaScript Destructuring Assignment (JavaScript解构赋值)

Object and Array are the two frequently used data structures of JavaScript. (Object和Array是JavaScript的两个常用数据结构。)

With the help of the objects, you can create an entity storing data items by key. With the help of the arrays, you can assemble data items into an ordered collection. (借助对象,您可以创建一个按键存储数据项的实体。借助数组,您可以将数据项组装到有序集合中。)

In case of passing those to a function, it might need an object and array not as a whole but some individual pieces. (如果将这些传递给函数,则可能需要一个对象和数组,而不是作为一个整体,而是一些单独的部分。)

The literal expressions of the object and the array allow creating ad hoc packages. Here is the syntax:

const x = [1, 2, 3, 4, 5];

The destructuring assignment is a unique syntax that helps “to unpack” objects or arrays into a group of variables. Destructuring can also operate efficiently with complex functions, default values, and more. (解构赋值是一种独特的语法,有助于将对象或数组“解包”到一组变量中。破坏也可以高效地操作复杂函数、默认值等。)

The destructuring assignment uses the following syntax:

const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1 
console.log(z); // 2

You can find similar features in other languages too. For example, in Python or Perl. (您也可以在其他语言中找到类似的功能。例如,在Python或Perl中。)

Now, let’s have a look at the example of the array destructure into variables:

// we have an array with the name and surname
let arr = ["John", "Doe"];
// destructuring assignment
// sets firstname = arr[0]
// and surname = arr[1]
let [firstname, surname] = arr;
console.log(firstname); // John
console.log(surname); // Doe

As a result, it is possible to work with variables instead of array members. (因此,可以使用变量而不是数组成员。)

will work even greater if you combine it with split or other methods for array-returning:

let [firstName, surname] = "John Doe".split(' ');

Note that destructuring is not the same as “destructive”. (请注意,破坏与“破坏性”不同。)

We call it destructuring as it “destructurizes” through the method of copying items into variables. (我们称之为解构,因为它通过将项目复制到变量的方法“解构”。)

Here is a shorter way to write:

// let [firstName, surname] = arr;
let firstName = arr[0];
let surname = arr[1];

Take into consideration that you can throw away unwanted elements by using an extra comma, like this:

// second element is not needed
let [name, age , profession] = ["David", "23", "programmer"];
console.log(profession); // programmer

It can work with any iterable on the right-side:

let [a, b, c] = "abc"; // ["a", "b", "c"]
let [one, two, three] = new Set([1, 2, 3]);

Moreover, you can use any assignables at the left side. (此外,您可以在左侧使用任何可分配项。)

For example, the property of an object:

let user = {};
[user.name, user.surname] = "John Doe".split(' ');
console.log(user.name); // John

Another useful thing is that it is possible to use the Object.entries(obj) method with destructuring for looping over keys-and-values of an object. (另一个有用的事情是,可以使用Object.entries (obj)方法和析构来循环对象的键和值。)

Here is an example:

let user = {
 name: "Maria",
 age: 25
};
// loop over keys-and-values
for (let [key, value] of Object.entries(user)) {
 console.log(`${key}:${value}`); // name:Maria, then age:25
}

The rest ‘…’

The rest ‘…’ (还忘了什么别的吗?)

In case it is necessary to get not only the first values but also to assemble all the followings, you have the option of adding another parameter for getting “the rest” by just using three dots “…”, like this:

let [name1, name2, ...rest] = ["John", "Doe", "doctor", "surgeon"]; 
console.log(name1); // John
console.log(name2); // Doe
// Note that type of `rest` is Array.
console.log(rest[0]); // doctor
console.log(rest[1]); // surgeon
console.log(rest.length); // 2

Default Values (默认值)

In case there are fewer values in the array than variables in the assignment, no error will occur. The values that are absent will be considered undefined:

let [firstName, surname] = [];
console.log(firstName); // undefined
console.log(surname); // undefined

If you want a default value for replacing the one that is missing, use the = sign, as follows:

// default values
let [name = "David", surname = "Smith"] = ["Peter"];
console.log(name); // Peter (from array)
console.log(surname); // Smith (default used)

Destructuring an Object

Destructuring an Object (破坏对象)

You can use the destructuring assignment with objects, as well, by using the following basic syntax:

let {  var1,  var2} = {  var1: …,  var2: …}

On the right side, there is an existing object that is necessary to split into variables. On the left side, there is a pattern for matching properties. The three dots sign {…} includes a group of variable names.

Here is an example:

let options = {
 title: "Car",
 model: "BMW M5",
 year: 2020
};
let {
 title,
(title)
 model,
(n.典型 ,范例,模范, 示范)
 year
} = options;
console.log(title); // Car
console.log(model); // BMW M5
console.log(year); // 2020

The properties options.title, options.width and options.height are assigned to matching variables. The arrangement doesn’t matter. This option will also work:

// changed the order in let {...}
let {
 year,
(年)
 model,
(n.典型 ,范例,模范, 示范)
 title
} = {
 title: "Car",
 model: "BMW M5",
 year: 2020
}

For assigning a property to a variable with different name, then you can act like this:

let options = {
 title: "Car",
 model: "BMW M5",
 year: 2020
}; 
// { sourceProperty: targetVariable }
let {
 model: m,
 year: y,
 title
} = options; 
// width -> m
// height -> y
// title -> title 
console.log(title); // Car
console.log(m); // BMW M5
console.log(y); // 2020

For possible missing properties, you have the option of setting default values using the sign of “=”, as follows:

let options = {
 title: "Car"
}; 
let {
 model = "BMW M5",
(model = "宝马M5",)
 year = 2020, 
(Year 2020)
 title
} = options; 
console.log(title); // Car
console.log(model); // BMW M5
console.log(year); // 2020

The default values might be any expressions or function calls. (默认值可以是任何表达式或函数调用。)

In case there is a complex object with a range of properties, you may choose to extract what you need, as follows:

let options = {
 title: "Car",
 model: "BMW M5",
 year: 2020
};
// only extract title as a variable
let {
 title
} = options; 
console.log(title); // Car

The Rest Pattern “…”

The Rest Pattern “…” (其余模式“…”)

Another scenario can also happen: the quantity of the object properties is more than the variables you have. In such cases, you can use the rest pattern. But, note that it works only on modern browsers.

Here is the example:

let options = {
 title: "Book",
 page: 200,
 species : "scientific"
}; 
// title = property named title
// rest = object with the rest of properties
let {
 title,
(title)
 ...rest
} = options; 
// now title="Book", rest={page: 200, species: scientific}
console.log(rest.page); // 200
console.log(rest.species); // scientific

Nested Destructuring

Nested Destructuring (嵌套破坏)

Imagine that an array or an object includes other nested arrays or objects. More complex, left-side patterns might be used for extracting deeper portions. (想象一下,数组或对象包括其他嵌套数组或对象。更复杂的左侧图案可用于提取更深的部分。)

In the example below, options contain another object in the property views and array in the property items:

let options = {
 views: {
   model: "sport",
   year: 2020
 },
 items: ["Car", "Bike"],
 extra: true
}; 
// destructuring assignment split in multiple lines for clarity
let {
 views: { // put size here
   model,
(n.典型 ,范例,模范, 示范)
   year
(年)
 },
 items: [item1, item2], // assign items here
 title = "Car&Bike" // not present in the object (default value is used)
} = options; 
console.log(title); // Car&Bike
console.log(model); // sport
console.log(year); // 2020
console.log(item1); // Car
console.log(item2); // Bike

It’s important to know that all the properties of options object except extra (it’s absent at the left side), are assigned to matching variables. (重要的是要知道,除了额外的(它在左侧不存在)之外,选项对象的所有属性都分配给匹配的变量。)

So, the model, year, item1, item2, and title are of the same value. But, no variables exist for views and items. (因此, model、year、item1、item2和title具有相同的值。但是,视图和项不存在变量。)

The Parameters of Smart Function

The Parameters of Smart Function (智能功能的参数)

Sometimes a function has many parameters, and most of them are optional. But, let’s see that a function creates a menu. It will have a height, width, items list, a title, and more. (有时一个函数有很多参数,其中大多数是可选的。但是,让我们来看看一个函数创建了一个菜单。它将具有高度、宽度、项目列表、标题等。)

We don’t recommend you to write the function, like this:

function showBook(title = "Javascript", page = 200,  species : "programming"
, items = []) {
 // ...
}

The main problem is remembering the order of the arguments. Another problem is to find a way of calling a function when the majority of the parameters are good by default. (主要问题是记住参数的顺序。另一个问题是找到一种在大多数参数默认情况下良好的情况下调用函数的方法。)

The most optional action is passing parameters as an object. The function will destructurize them into a variable at once, like this:

// we pass object to function
let options = {
 title: "Js book",
 items: ["Item1", "Item2"]
};
function showBook({
 title = "Javascript",
 pages = 200,
 species  = "programming",
(species = "编程",)
 items = []
}) {
 // title, items – taken from options,
(//title, items –取自options,)
 // pages, species – defaults used
(//pages, species –使用的默认值)
 console.log(`${title} ${species} ${pages}`); // Javascript programming 200
console.log(items); // Item1, Item2
}
showBook(options);

There is another, more complex way of destructuring, including nested objects and colon mappings. (还有另一种更复杂的解构方式,包括嵌套对象和结肠映射。)

For instance:

let options = {
 title: "Js  book"
}; 
function showBook({
 title = "Javascript",
 p = 200, //pages goes to p
(p = 200,//pages goes to p)
 s = "programming", // species goes to s
}) {
 console.log(`${title} ${s} ${p}`); // Javascript programming 200
} 
showBook(options);

The full syntax will look like this:

function ({
 incomingProperty: varName = defaultValue
   ...
})

As you can see, it’s the same as for a destructuring assignment. (正如您所看到的,这与解构任务相同。)

Then, for the parameters’ object, there will be a variable varName for incomingProperty. (然后,对于参数的对象,将为incomingProperty提供一个变量varName。)

Destructuring like this considers that showBook() has no argument. In case you want all the values by default, then specify an empty object, like this:

showBook({}); // ok, all values are default
showBook(); // this would give an error

It is possible to fix it by setting {} the default value the object of parameters.

For instance:

function showBook({
 title = "Book",
(title = "书籍",)
 species = "programming",
(species = "编程",)
 pages = 200
} = {}) {
 console.log(`${title} ${species} ${pages}`);
}
showBook(); // Book programming 200


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部