This article brings you relevant knowledge aboutjavascript, 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.
[Related recommendations:javascript video tutorial,web front-end】
Object (Object
) and array (Array
) are the two most commonly used data structures inJavaScript
. 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 useDestructuring assignmentto unpack the object/array and obtain part of its internal data. The following uses cases to introduce the application of destructuring assignment in programming.
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)
The code execution result is as follows:
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 thesplit
function, which is elegant and high-end:
let [x, y] = 'hello world'.split(' ')console.log(x, y)
The code execution results are as follows:
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]
{1}
and{2}
in the above code are completely equivalent, but the destructuring and assignment method is more concise.
If we use destructuring assignment, we hope to get the1
,3
th element of the array, but not the first2
elements, what should we do?
For example:
let [x, ,z] = ['first','second','third']console.log(x,z)
The code execution result is as follows:
In this way, commas are used to avoid the second element.
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)
Code Execution result:
#Destructuring assignment will iterate the value on the right and then assign the value to the variable on the left.
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)
Code execution result:
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".
Object.entries(obj)
method will return the attribute list of the objectobj
, 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)}
Code execution result:
Due to theMap
object It is iterable itself, so you can directly use thefor...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)}
Code execution result:
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}`)
Code execution result:
During the process of performing destructuring assignment, there are two situations:
undefined
Fill;...
to collect;There are more elements on the left than on the right :
let [a,b,c] = 'ab'console.log(a,b,c)
Code execution result:
可见最后一个变量c
被赋值undefined
。
我们也可以为多余的左侧变量赋予默认值,举个例子:
let[a=0,b=0,c=0] = 'ab'console.log(c)
代码执行结果如下:
右侧多于左侧:
let [a, b] = 'abcd'console.log(a,b)
代码执行结果如下:
这里就没什么可解释的了。
但是,如果我们希望获得其他元素应该怎么做呢?
举例如下:
let [a, b, ...others] = 'abcdefg'console.log(others)
代码执行结果:
这里的变量others
就将所有剩余选项全部都收集了起来,others
可以是任何合法的变量名,不局限于others
本身。
解构语法同样使用于对象,只不过语法上稍有不同:
let {var1, var2} = {...}
举个例子:
let country = { name:'China', desc:'Beautiful'};let {name,desc} = country;console.log(name,desc)
代码执行结果:
**注意:**这里的变量顺序是没有影响的,我们也可以交换name
和desc
的位置,如:
let {desc,name}=country;
代码的执行结果并没有什么变化。
当然我们也可以指定变量和属性的映射,例如:
let country = { name:'China', desc:'Beautiful'}//对应的规则:{对象属性:目标变量}let {name:desc,desc:name} = country;console.log(`name:${name},desc:${desc}`)
代码执行结果:
这样我们就强行交换了变量和属性之间的映射方式,或许下面的例子更直观:
let obj = { x:'xiaoming', y:'18'}let {x:name,y:age}=obj;console.log(`name:${name},age:${age}`)
代码执行结果:
和数组一样,我们也可以使用=
为变量指定默认值。
举例如下:
let obj = { name:'xiaoming', age:18}let {name='xiaohong',age=19,height=180} = obj console.log(height)
代码执行结果:
这样,即使对象没有对应的属性,我们同样可以使用默认值代替。
我们还可以结合映射和默认值:
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}`)
代码执行结果:
和数组一样,我们可以取对象的一部分属性:
let obj = { x:'x', y:'y', z:'z'}let {x:name}=obj console.log(name)
我们还可以使用...
将剩余的属性重新打包为一个新对象:
let obj = { x:'x', y:'y', z:'z'}let {x,...others}=obj console.log(others)
代码执行结果:
可能有写童鞋已经发现了,我们在使用解构操作时,总是把一个对象赋值给一个使用let
新定义的变量,例如:let {...} = obj
。
如果我们使用已经存在的对象,会发生什么事呢?
let a,b,c;//定义三个变量{a,b,c} = {a:'a',b:'b',c:'c'}console.log(a,b,c)
代码执行结果如下:
为什么会出现这种错误呢?
这是因为JavaScript
会把主代码流中的{...}
作为一个代码块,代码块是一个独立的代码空间,用于语句的分组。
案例如下:
{ let a = 1; let b = 2; ...}
上例中的{a,b,c}
就被错误的当成了这样的代码块,为了告诉引擎这不是一个代码块,我们可以这样:
let a,b,c;//定义三个变量({a,b,c} = {a:'a',b:'b',c:'c'})//加括号console.log(a,b,c)
代码执行结果如下:
如果对象出现了嵌套,相应的我们也可以使用对应的嵌套层次进行解析:
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)
代码执行结果:
有些情况下,一个函数需要非常多的参数,这不仅会让程序猿记忆困难,同时也会让代码变的冗长。
例如:
function createWin(title="Untitled",width=100,height=200,items=[]){ ...}
这种情况下,调用函数会变的非常困难。更令人苦恼的是,通常这些参数只要保持默认就可以了,而我们还要费尽心机的重写它们。就像这样:
createWin(title="Untitled",width=100,height=200,items=['i','j','k'])
解构赋值可以帮助我们解决这些问题,我们可以把对象传递给函数,而函数会自动的把对象解析为参数:
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)//只需要传递一个对象
【相关推荐: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!