I have a function which looks like this:
function helo(a,b){
if(a)
{
//do something
}
if(b)
{
//do something
}
}
Now if I want to specify which parameter has to be passed while calling helo, how do I do it in javascript, ie
If I want to send only parameter b, how do I call the function helo?
helo(parameterB);
Right now parameter a takes the value
Your best bet would be to just pass an object containing all parameters:
function myFunction(parameters){
if(parameters.a) {
//do something
}
if(parameters.b) {
//do something
}
}
Then you can call the function like this:
myFunction({b: someValue}); // Nah, I don't want to pass `a`, only `b`.
In case you want to be able to pass falsy
values as parameters, you're going have to change the if
sa bit:
if(parameters && parameters.hasOwnProperty('a')){
//do something
}
Another option would be to simply pass null
(or any other falsy
value) for parameters you don't want to use:
helo(null, parameterB);
在JavaScript中,参数根据顺序进行匹配,因此如果您只想传递第二个参数,则必须先将第一个参数保留为空
helo(null,parameterB);
Instead of passing multiple distinct arguments, you can pass in a single argument, which is an object.
For Example:
function helo(args){
if(args.a){ ... }
if(args.b){ ... }
}
helo({b: 'value'});
You can use either of the below two syntax:
helo(null,parameterB);
or
helo(undefined,parameterB);
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.