什么是解构分配及其用途? [英] What is destructuring assignment and its uses?
问题描述
我一直在阅读解构分配在ES6中引入。
I have been reading about Destructuring assignment introduced in ES6.
这种语法的目的是什么,它为什么被引入,以及在实践中如何使用它的一些例子?
What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?
推荐答案
什么是解构分配?
What is destructuring assignment ?
解构赋值 语法是一个JavaScript表达式,可以将数组中的值或对象的属性解包为不同的变量。
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
一些用例
Some use cases
1。要从Objects中获取变量值,数组
1. To get values in variable from Objects,array
let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)
let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '\n', second, '\n', rest)
2。将任何地方的数组与另一个数组合并。
2. To combine an array at any place with another array.
let arr = [2,3,4,5]
let newArr = [0,1,...arr,6,7]
console.log(newArr)
3。仅更改对象中所需的属性
3. To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]
let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))
console.log(op)
4。创建对象的浅层副本
4. To create a shallow copy of objects
let obj = {a:1,b:2,c:3}
let newObj = {...obj}
newObj.a = 'new Obj a'
console.log('Original Object', obj)
console.log('Shallow copied Object', newObj)
<强> 5。拆分字符串
5. To split string
let str = 'abcdefghijklmonpqrstuvwxyz'
console.log("Alphabet array ---\\\n",[...str])
6。从对象获取动态密钥的值
6. To get dynamic key's value from object
let obj = {a:1,b:2,c:3}
let key = 'c'
let {[key]:value} = obj
console.log(value)
7。使用某些默认值从其他对象构建对象
7. To build an object from other object with some default values
let obj = {a:1,b:2,c:3}
let newObj = (({d=4,...rest} = obj), {d,...rest})
console.log(newObj)
8。交换值
8. To swap values
const b = [1, 2, 3, 4];
[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
console.log(b);
的 9。获取对象的子集
9. To get a subset of an object
-
9.1 对象的子集:
const obj = {a:1, b:2, c:3},
subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function
console.log(subset);
9.2使用逗号运算符和destrcturing获取对象的子集:
9.2 To get a subset of an object using comma operator and destrcturing:
const object = { a: 5, b: 6, c: 7 };
const picked = ({a,c}=object, {a,c})
console.log(picked); // { a: 5, c: 7 }
10。要进行数组到对象转换:
10. To do array to object conversion:
const arr = ["2019", "09", "02"],
date = (([year, day, month]) => ({year, month, day}))(arr);
console.log(date);
11。 在功能中设置默认值。(阅读此答案以获取更多信息)
11. To set default values in function. (Read this answer for more info )
function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){
console.log(settings.i)
console.log(settings.i2)
}
someName('hello', {i:'#123'})
someName('hello', {i2:'#123'})
这篇关于什么是解构分配及其用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!