简体   繁体   English

将最后一个参数传递给 function - JavaScript

[英]Pass the last parameter to function - JavaScript

If I have a function with two different parameters, how can I make it so that if I input only one parameter, it will use the input as the second parameter rather than the first parameter?如果我有一个 function 有两个不同的参数,我怎样才能使如果我只输入一个参数,它将使用输入作为第二个参数而不是第一个参数? For example, if I have this function:例如,如果我有这个 function:

function x(a=1,b=2) {
    console.log(a);
    console.log(b);
}

and call x(3) , it will use the 3 for a and return "3, 2"并调用x(3) ,它将使用 3 作为a并返回 "3, 2"

x(3);

=> 3
   2

I want it so that the function instead uses the 3 for the b parameter, and therefore returns "1, 3"我想要它,以便 function 使用 3 作为b参数,因此返回“1, 3”

x(3);
=> 1
   3

If you change your method to use a destructured object , you can pass an object with just the properties you wish to and default the rest如果您更改方法以使用解构的 object ,您可以传递一个 object ,其中只包含您希望的属性并默认 rest

 function x({a=1,b=2} = {}){ console.log("a",a); console.log("b",b); } x(); x({a:10}) x({b:20})

Use object destructuring approach使用object 解构方法

 let a,b; /* * define variable to avoid overwrite in large application */ function x({a=1,b=2} = {}){ console.log( { a } ); console.log( { b } ); } x({b:20}) /* Passed only 'b' here */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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