什么是销毁工作?
该 解构赋值 语法是Javascript表达式,使得它可以从阵列解压缩的值,或从属性的对象,为不同的变量。
- [MDN]
优点
*答 *: 使代码简明易懂。
B. 我们可以轻松避免重复破坏表达。
一些用例
1.要从Objects,array获取变量中的值
let obj = { 'a': 1,'b': {'b1': '1.1'}}let {a,b,b:{b1}} = objconsole.log('a--> ' + a, 'nb--> ', b, 'nb1---> ', b1)let obj2 = { foo: 'foo' };let { foo: newVarName } = obj2;console.log(newVarName);let arr = [1, 2, 3, 4, 5]let [first, second, ...rest] = arrconsole.log(first, 'n', second, 'n', rest)2.在任何地方将一个阵列与另一个阵列合并。
let arr = [2,3,4,5]let newArr = [0,1,...arr,6,7]console.log(newArr)
3.仅更改对象中的所需属性
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.创建对象的浅表副本
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.将参数中的值提取到独立变量中
// Object destructuring:const fn = ({ prop }) => { console.log(prop);};fn({ prop: 'foo' });console.log('------------------');// Array destructuring:const fn2 = ([item1, item2]) => { console.log(item1); console.log(item2);};fn2(['bar', 'baz']);console.log('------------------');// Assigning default values to destructured properties:const fn3 = ({ foo="defaultFooVal", bar }) => { console.log(foo, bar);};fn3({ bar: 'bar' });6.从对象获取动态键值
let obj = {a:1,b:2,c:3}let key = 'c'let {[key]:value} = objconsole.log(value)7.从具有某些默认值的其他对象构建对象
let obj = {a:1,b:2,c:3}let newObj = (({d=4,...rest} = obj), {d,...rest})console.log(newObj)8.交换价值
const b = [1, 2, 3, 4];[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2console.log(b);
9.获取对象的子集
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 使用逗号运算符并解构来获取对象的子集:
const object = { a: 5, b: 6, c: 7 };const picked = ({a,c}=object, {a,c})
console.log(picked); // { a: 5, c: 7 }
10.做数组到对象的转换:
const arr = ["2019", "09", "02"],date = (([year, day, month]) => ({year, month, day}))(arr);console.log(date);11.在功能中设置默认值。
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'})12.获取属性,例如length
从数组,函数名称,参数数量等。
let arr = [1,2,3,4,5];let {length} = arr;console.log(length);let func = function dummyFunc(a,b,c) { return 'A B and C';}let {name, length:funcLen} = func;console.log(name, funcLen);


