什么是解构赋值及其用途? [英] What is destructuring assignment and its uses?

查看:28
本文介绍了什么是解构赋值及其用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读关于解构赋值 在 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?

推荐答案

什么是解构赋值?

解构赋值语法是一种 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.

- MDN

优势

A. 使代码简洁且更具可读性.

A. Makes code concise and more readable.

B.我们可以轻松避免重复破坏表达式.

B. We can easily avoid repeated destructing expression.

一些用例

1.要从对象中获取变量中的值,数组

let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '
b--> ', b, '
b1---> ', 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, '
', second, '
', 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.获取对象的子集

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 使用逗号运算符和解构获取对象的子集:

9.2 To get a 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.在函数中设置默认值.(阅读此答案了解更多信息)

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'})

12.从数组中获取诸如length、函数名称、参数数量等属性.

12. To get properties such as length from an array, function name, number of arguments etc.

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);

这篇关于什么是解构赋值及其用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆