简体   繁体   English

javascript定义参数

[英]javascript define arguments

I am trying to create a function in JS that is taking a lot of arguments but does not always use all of them. 我正在尝试在JS中创建一个函数,该函数需要很多参数,但并不总是使用所有参数。 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 = ''}={}) 如果您需要设置默认参数,则可以通过以下方式执行此function foo({arg = '', arg2 = ''}={})

You can pass in null as some of the parameters if they are not needed. 如果不需要这些参数,则可以传入null作为某些参数。

 function foo(arg1, arg2, arg3){ console.log(arg1, arg2, arg3); } foo(null, 30, null); 

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

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