JavaScript什么是解构赋值及其用途?

我一直在阅读有关ES6中引入的解构分配的信息。

该语法的目的是什么,为什么要引入它,以及在实践中如何使用它的一些示例?

回答:

该 语法是JavaScript表达式,使得它可以从阵列解压缩的值,或从属性的对象,为不同的变量。

  • [MDN]

使代码简明易懂。

我们可以轻松避免重复破坏表达。

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)

let arr = [2,3,4,5]

let newArr = [0,1,...arr,6,7]

console.log(newArr)

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)

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)

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

let obj = {a:1,b:2,c:3}

let key = 'c'

let {[key]:value} = obj

console.log(value)

let obj = {a:1,b:2,c:3}

let newObj = (({d=4,...rest} = obj), {d,...rest})

console.log(newObj)

const b = [1, 2, 3, 4];

[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2

console.log(b);

  • 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 }

const arr = ["2019", "09", "02"],

date = (([year, day, month]) => ({year, month, day}))(arr);

console.log(date);

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

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什么是解构赋值及其用途? 的全部内容, 来源链接: utcz.com/qa/432143.html

回到顶部