我一直在阅读 Destructuring assignment在 ES6 中引入。
此语法的目的是什么,为什么引入它,以及如何在实践中使用它的一些示例?
最佳答案
What is destructuring assignment ?
解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解包到不同的变量中。
- MDN
Advantages
A. 使代码简洁且更具可读性。
B.我们可以轻松避免重复破坏表达式。
Some use cases
1.要从对象、数组中获取变量值
let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.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] = arr
console.log(first, '\n', second, '\n', rest)
// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);
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} = obj
console.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 2
console.log(b);
9.获取对象的子集
9.1 subset of an object :
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 获得 subset of an object using comma operator and destructuring :
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. To set default values in function. (阅读此答案了解更多信息)
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.从数组、函数名称、参数数量等获取长度
等属性。
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);
关于javascript - 什么是解构赋值及其用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847993/