向javascript函数传递的参数过多时会收到警告

编程入门 行业动态 更新时间:2024-10-26 18:29:23
本文介绍了向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函数传递的参数过多时会收到警告

本文发布于:2023-11-25 12:18:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629719.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时会   函数   参数   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!