给定一个正常的函数;
function descriptions(awesome, cool, alright){
return (awesome || "no one") + " is awesome. " + cool + " is cool. " +
+ alright + " is alright";
}
descriptions("jane", "jack", "jefferson");
//returns "jane is awesome. jack is cool. jefferson is alright."
我想使用相同的函数,但只想像这样将最后两个参数传递给它:
descriptions(cool : "john", alright : "jane"); //I would like a statement similar to this that works.
//should return "no one is awesome. jack is cool. jefferson is alright."
如何完成上述操作?
最佳答案
使用对象解构可以实现语法上不同但语义上相似的东西
function descriptions({ awesome = 'no one', cool, alright }) {
return awesome + " is awesome. " + cool + " is cool. " +
+ alright + " is alright";
}
然后您只需使用具有相应属性的对象调用它:
descriptions({ cool: 'a', alright: 'b'});
关于javascript - 如何选择在函数中将变量分配给哪个参数? -Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36782872/