tnk*_*nkh 4 javascript ecmascript-6
Hi I have to admit that I am still grasping many ES6 syntax even though I have used a fair amount of them.
For example, I understand that you can do console.log(multiply(5)) to get the result of a given function of
function multiply(a, b = 1) {
return a * b;
}
Run Code Online (Sandbox Code Playgroud)
But let say you have
function multiply(a, b = 1, c) {
return a * b * c;
}
Run Code Online (Sandbox Code Playgroud)
Obviously you can't do (console.log(multiply(5,,5)). In this case, is rearranging the arguments position in the function to become function multiply(a, c, b = 1) the only possible way? Or is there any other smarter way?
小智 6
您可以传递undefined使用默认值:
function multiply(a, b = 1, c) {
return a * b * c;
}
multiply(2, undefined, 3); // 6
Run Code Online (Sandbox Code Playgroud)
您可以阅读有关默认参数值的信息,并在MDN上查看更多示例
Another option is to pass a single object with default property assignment instead of multiple separate arguments:
function multiply({ a, b = 1, c }) {
return a * b * c;
}
console.log(multiply({
a: 3,
b: 4,
c: 5
}));
console.log(multiply({
a: 3,
c: 5
}));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
485 次 |
| 最近记录: |