个人学习心得 - 解构赋值的几种妙用

81 阅读1分钟

优化对象属性值获取

const fUserConcat = (x) => `user${x}`;
const oTest = {
    [fUserConcat('Name')]: 'Nicky',
    [fUserConcat('Action')]: 'eating',
    [fUserConcat('Age')]: 10
}

function fUserPatch({userName, userAction}) {
    console.log(`${userName} loves ${userAction}`);
}
fUserPatch(oTest);
//Nicky loves eating

数组解构

const aTest = [1, 2, 3, 4];
const [nFirst, nSecond] = aTest;  // 等价于却优于 const [0: nFirst, 1: nSecond] = aTest;
console.log('nFirst', nFirst);
//nFirst 1

返回值用对象解构,不用记住所有属性,获取更方便

const oTest = {
    left: 10,
    right: 10,
    top: 10,
    bottom: 10
};
function fObjectOutput(input) {
    const {left, right, top, bottom} = input;
    return {left: left + 10, right: right + 10, top: top + 5, bottom}
};
const {left: nLeft, top: nTop, bottom: nBottom} = fObjectOutput(oTest);
console.log('nLeft', nLeft);
console.log('nTop', nTop);
console.log('nBottom', nBottom);
//nLeft 20
//nTop 15
//nBottom 10