简体   繁体   中英

Default destructed function parameters in one object in JavaScript

is there a possibility to access ALL destructed function parameters in one object?

So I have this function head:

function coolFunctionName({test1 = "foo", test2 = "bar"})

I want to access them in one object. arguments doesn't work, because there aren't stored the default parameters which doesn't have a value in function call.

Is there a good and clean way to do that?

EDIT: I don't need the destructed parameters. I just want to have all of them in one object.

Inspired from Faly's answer I think I've got the "cleanest" solution:

function coolFunctionName(options = {}){
    options = Object.assign({
        test1: "foo",
        test2: "bar
    }, options);
}

I have the parameter in one object and I have not to write multiple value names. I'm not happy about that because it's not in the function head but it's the best solution I've found.

To achieve expected result, use below option of setting default value inside function

 function coolFunctionName(x){ x.test1 = x.test1 || 'foo' x.test2 = x.test2 || 'bar' console.log(x) } let z ={} coolFunctionName(z); let y ={test1:"zzz", test2:"yyy"} coolFunctionName(y); 

codepen- https://codepen.io/nagasai/pen/KxBmod?editors=1011

All you can do is:

function coolFunctionName({test1 = "foo", test2 = "bar"}) {
    let arguments = { test1, test2 };
    /* Do whatever you want with arguments */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM