javascript ES6 - 解构函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript ES6 - 解构函数相关的知识,希望对你有一定的参考价值。

function convertCurrency(amount) {
    const converted = {
        USD: amount * 0.76,
        GBP: amount * 0.53,
        AUD: amount * 1.01,
        MEX: amount * 13.30
    };
    return converted;
}

// Destructure the returned object directly, order doesn't matter!
const { USD, MEX, AUD, GBP } = convertCurrency(100);
console.log(USD, MEX, AUD, GBP);

function returnArray() {
    return ['hulk', 'thor', 'iron man', 'spider man', 'black widow'];
}

// Destructure returned array directly, naming is based on position. The `team`
// variable holds an array with everyone after the hulk and thor.
const [ hulk, thor, ...team ] = returnArray();
console.log(hulk, thor, team);


// Here we add an object as default argument for the function and we immediately
// destructure the object that is passed into the function. This way the order 
// doesn't matter anymore and you can ommit any value you don't need. 
// When we don't pass in anything into the function we do want something to destructure
// on, that's why we have an empty object in the arguments.
function tipCalc({ total = 100, tip = 0.15, tax = 0.13 } = {}) {
    return total + (tip * total) + (tax * total);
}

const bill = tipCalc({ tip: 0.20, total: 200 });
console.log(bill);


以上是关于javascript ES6 - 解构函数的主要内容,如果未能解决你的问题,请参考以下文章

ES6解构

JavaScript ES6 - 解构赋值

JavaScript ES6 - 解构赋值

JavaScript ES6 - 解构赋值

高级JavaScript第篇

ES6基础-变量的解构赋值