I am trying to create a function in JS that is taking a lot of arguments but does not always use all of them. What I would like to do is define which argument I am putting a refrence in for. This is what I am thinking but not working like I would like it to.
function foo(arg1, arg2, arg3){
let arg1 = arg1;
let arg2 = arg2;
let arg3 = arg3;
}
foo(arg2:'sets value of arg2');
I would like to be able to skip putting in an argument for the first position and only pass info for the second argument. How can I do this?
You could spread syntax ...
a sparse array with the value for the wanted argument without changing the function's signature.
function foo(arg1, arg2, arg3){ console.log(arg1, arg2, arg3) } foo(...[, 42]);
Or use an object with the key for a specified element
function foo(arg1, arg2, arg3){ console.log(arg1, arg2, arg3) } foo(...Object.assign([], { 1: 42 }));
Try this:
It would require the caller to pass an object.
function foo({arg, arg2}={}) { let arg_1 = arg; let arg_2 = arg2; console.log(arg_1); console.log(arg_2); // Code } foo({arg2: 2});
if you need to set the default parameters you can do it this way function foo({arg = '', arg2 = ''}={})
You can pass in null
as some of the parameters if they are not needed.
function foo(arg1, arg2, arg3){ console.log(arg1, arg2, arg3); } foo(null, 30, null);
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.