Home > Web Front-end > JS Tutorial > Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

WBOY
Release: 2022-06-22 12:04:08
forward
1892 people have browsed it

This article brings you relevant knowledge about javascript, which mainly organizes issues related to destructuring and assigning objects and arrays, including array destructuring, object destructuring, function parameter parsing, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

[Related recommendations: javascript video tutorial, web front-end

Object (Object ) and array (Array) are the two most commonly used data structures in JavaScript. The common feature of both is that they can store a large amount of data.

The problem is that when we pass parameters and calculate them, we may only need part of the object and array, not the entire object/array.

At this time, you need to use Destructuring assignment to unpack the object/array and obtain part of its internal data. The following uses cases to introduce the application of destructuring assignment in programming.

Array destructuring

The so-called array destructuring is to obtain part of the data that is useful to us in the array. For example:

let arr = ['first','second']let [x, y] = arr //解构操作console.log(x,y)
Copy after login

The code execution result is as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

The content of the code is very simple. It assigns the contents of the array to two variables and then outputs them.

Array destructuring can also be used in conjunction with the split function, which is elegant and high-end:

let [x, y] = 'hello world'.split(' ')console.log(x, y)
Copy after login

The code execution results are as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Destructuring does not change the original array

Destructuring can also be called "destructuring assignment". Its essence is to copy the elements of the array to variables, so the original array does not change in any way.

let [x, y] = arr //{1}let x = arr[0]   //{2}let y = arr[1]
Copy after login

{1} and {2} in the above code are completely equivalent, but the destructuring and assignment method is more concise.

Ignore array elements

If we use destructuring assignment, we hope to get the 1, 3th element of the array, but not the first 2 elements, what should we do?

For example:

let [x, ,z] = ['first','second','third']console.log(x,z)
Copy after login

The code execution result is as follows:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

In this way, commas are used to avoid the second element.

Iterable objects use destructuring

Destructuring assignment is not necessarily used on arrays, it can be used on any iterable object, for example:

let [x, y, z] = 'xyz'let [a, b, c] = new Set(['a','b','c'])console.log(x,y,z)console.log(a,b,c)
Copy after login

Code Execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

#Destructuring assignment will iterate the value on the right and then assign the value to the variable on the left.

Assign a value to any variable

The right side of the = of the destructuring assignment can be any and iterated object, while the left side can be any variable that can be assigned a value, and Not limited to simple variables.

Give a chestnut:

let country = {};[country.name, country.desc] = 'China Beautiful'.split(' ')console.log(country.name,country.desc)
Copy after login

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Note: The points in the first line of code The number must be added, otherwise you will encounter an error! For details, you can learn about "JavaScript Syntax Structure".

Combined with the .entries() method

Object.entries(obj) method will return the attribute list of the object obj, we can also Destructuring syntax is used here:

let country = {
    name:'China',
    desc:'a beautiful country'}for(let[k, v] of Object.entries(country)){
    console.log(k,v)}
Copy after login

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Combined with Map

Due to the Map object It is iterable itself, so you can directly use the for...of syntax combined with the destructuring syntax:

let map = new Map()map.set('name','China')map.set('desc','Beautiful Country')for(let [k, v] of map){
    console.log(k,v)}
Copy after login

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Variable exchange

There is a famous technique for destructuring assignment, exchanging the values ​​​​of two variables:

let a = 1;let b = 2;[a,b]=[b,a]console.log(`a=${a},b=${b}`)
Copy after login

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

Extra elements

During the process of performing destructuring assignment, there are two situations:

  1. There are more elements on the left than on the right, and the value on the left uses undefinedFill;
  2. The elements on the right are more than the elements on the left. Ignore the excess. You can also use ... to collect;

There are more elements on the left than on the right :

let [a,b,c] = 'ab'console.log(a,b,c)
Copy after login

Code execution result:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

可见最后一个变量c被赋值undefined

我们也可以为多余的左侧变量赋予默认值,举个例子:

let[a=0,b=0,c=0] = 'ab'console.log(c)
Copy after login

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

右侧多于左侧:

let [a, b] = 'abcd'console.log(a,b)
Copy after login

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这里就没什么可解释的了。

但是,如果我们希望获得其他元素应该怎么做呢?

举例如下:

let [a, b, ...others] = 'abcdefg'console.log(others)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这里的变量others就将所有剩余选项全部都收集了起来,others可以是任何合法的变量名,不局限于others本身。

对象解构

解构语法同样使用于对象,只不过语法上稍有不同:

let {var1, var2} = {...}
Copy after login

举个例子:

let country = {
    name:'China',
    desc:'Beautiful'};let {name,desc} = country;console.log(name,desc)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

**注意:**这里的变量顺序是没有影响的,我们也可以交换namedesc的位置,如:

let {desc,name}=country;
Copy after login

代码的执行结果并没有什么变化。

属性变量映射

当然我们也可以指定变量和属性的映射,例如:

let country = {
    name:'China',
    desc:'Beautiful'}//对应的规则:{对象属性:目标变量}let {name:desc,desc:name} = country;console.log(`name:${name},desc:${desc}`)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这样我们就强行交换了变量和属性之间的映射方式,或许下面的例子更直观:

let obj = {
    x:'xiaoming',
    y:'18'}let {x:name,y:age}=obj;console.log(`name:${name},age:${age}`)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

默认值

和数组一样,我们也可以使用=为变量指定默认值。

举例如下:

let obj = {
    name:'xiaoming',
    age:18}let {name='xiaohong',age=19,height=180} = obj
console.log(height)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

这样,即使对象没有对应的属性,我们同样可以使用默认值代替。

我们还可以结合映射和默认值:

let obj = {
    x:'xiaoming',
    y:'18'}let {x:name='xxx',y:age=18,height:height=180}=obj;console.log(`name:${name},age:${age},height:${height}`)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

多余的属性

和数组一样,我们可以取对象的一部分属性:

let obj = {
    x:'x',
    y:'y',
    z:'z'}let {x:name}=obj
console.log(name)
Copy after login

我们还可以使用...将剩余的属性重新打包为一个新对象:

let obj = {
    x:'x',
    y:'y',
    z:'z'}let {x,...others}=obj
console.log(others)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

let陷阱

可能有写童鞋已经发现了,我们在使用解构操作时,总是把一个对象赋值给一个使用let新定义的变量,例如:let {...} = obj

如果我们使用已经存在的对象,会发生什么事呢?

let a,b,c;//定义三个变量{a,b,c} = {a:'a',b:'b',c:'c'}console.log(a,b,c)
Copy after login

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

为什么会出现这种错误呢?

这是因为JavaScript会把主代码流中的{...}作为一个代码块,代码块是一个独立的代码空间,用于语句的分组。

案例如下:

{
    let a = 1;
    let b = 2;
    ...}
Copy after login

上例中的{a,b,c}就被错误的当成了这样的代码块,为了告诉引擎这不是一个代码块,我们可以这样:

let a,b,c;//定义三个变量({a,b,c} = {a:'a',b:'b',c:'c'})//加括号console.log(a,b,c)
Copy after login

代码执行结果如下:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

多层解析

如果对象出现了嵌套,相应的我们也可以使用对应的嵌套层次进行解析:

let People = {
    head:{
        leftEye:'le',
        rightEye:'re'
    },
    hands:['left-hand','right-hand'],
    others:'others'}let {
    head:{
        leftEye,
        rightEye    },
    hands:[left_hand,right_hand],
    others} = People;console.log(leftEye,right_hand)
Copy after login

代码执行结果:

Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays

函数参数解析

有些情况下,一个函数需要非常多的参数,这不仅会让程序猿记忆困难,同时也会让代码变的冗长。

例如:

function createWin(title="Untitled",width=100,height=200,items=[]){
    ...}
Copy after login

这种情况下,调用函数会变的非常困难。更令人苦恼的是,通常这些参数只要保持默认就可以了,而我们还要费尽心机的重写它们。就像这样:

createWin(title="Untitled",width=100,height=200,items=['i','j','k'])
Copy after login

解构赋值可以帮助我们解决这些问题,我们可以把对象传递给函数,而函数会自动的把对象解析为参数:

let options = {
    title:'NewWin',
    width:200,
    height:100,
    items:['items1','items2']}//传入的对象会被解构成下面的参数样式//等价于{title="Untitled",width=100,height=200,items=[]} = optionsfunction createWin({title="Untitled",width=100,height=200,items=[]}){
   	  console.log(`title:${title},width:${width},height:${height},items:[${items}]`)}createWin(options)//只需要传递一个对象
Copy after login

【相关推荐:javascript视频教程web前端

The above is the detailed content of Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template