Get warning when passing too few arguments to a javascript function

故事扮演 提交于 2021-02-07 10:10:17

问题


Is there a tool that can help me detect when a javascript function is being passed too few arguments? As far as I can tell, neither JSLint nor JSHint provides this feature.

Just be make it clear, if I write:

some_method = function(x,y) {
  // ..do stuff
}
some_method(2);

I would like to be warned, that I might have to pass in another argument.


回答1:


You can't do that, all parameters are always optional and you can pass an indefinite amount of parameters to a parameterless function (through the arguments array).

But you can use the arguments array to test your own methods manually. You would have to add it to each method individually, since you can't reflect the amount of arguments in your method signature. So for this specific case you would use:

function test(x, y) {
  if (arguments.length !== 2)
    {
      console.log('error, invalid amount of args');
    }
}

test(1); // this will trigger the console.log and type the error.

If you really need parameter checking you could use something like TypeScript, where parameters are required by default.




回答2:


In case you want to get some optional param in function, you can passing the params as array, and can validate each array's value. Like this:

function action(param)
{
    var total_params = param.length;
    console.log(param);

    // do stuff
}

action(Array('param01',02, true, 'param04'));


来源:https://stackoverflow.com/questions/25364881/get-warning-when-passing-too-few-arguments-to-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!