向javascript函数传递的参数过多时会收到警告 [英] Get warning when passing too few arguments to a javascript function

查看:125
本文介绍了向javascript函数传递的参数过多时会收到警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种工具可以帮助我检测何时传递的javascript函数参数太少?据我所知,JSLint和JSHint都不提供此功能.

请明确指出,如果我写:

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

我想被警告,我可能不得不传递另一个论点.

解决方案

您无法做到这一点,所有参数始终是可选的,并且可以将不确定数量的参数传递给无参数函数(通过arguments数组). /p>

但是您可以使用arguments数组来手动测试您自己的方法.由于您无法在方法签名中反映参数的数量,因此您必须将其分别添加到每个方法中.因此,对于这种特定情况,您将使用:

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.

如果您确实需要参数检查,则可以使用TypeScript之类的工具,默认情况下需要使用参数.

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.

解决方案

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.

这篇关于向javascript函数传递的参数过多时会收到警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆