![](/img/trans.png)
[英]How do you know the value of the parameter in this javascript function ?
[英]In javascript how do I know what type of parameter(s) a function is expecting
在JavaScript中,我如何知道函数期望的参数类型 ? 有人说您正在调用函数,必须知道函数接受的参数类型,但我认为并非总是如此。
我唯一想到的就是使用Function.arguments并编写一些代码来查找参数的数量及其类型。 关于了解JavaScript函数期望的参数类型的最佳实践是什么。
这只是好的文档的来源。拥有一个API文档页面来告诉您的参数比以编程方式执行类似的操作要容易得多。
function derp(uno, dos) {
var error = [];
if (!uno) error.push("The first parameter, uno, needs to be a ...");
if (!dos) error.push("The second parameter, dos, needs to be a ...");
return error;
}
比对大量错误数组进行加密要容易得多。
您可以使用arguments对象将某些东西绑定在一起,但是JavaScript是动态类型的,因此您无法设置特定的类型。 您只能检查并返回错误,但必须在EVERY方法中调用它。
您可以尝试以下方法:
function greet(msg) {
if(!msg) throw "Parameter message is required !";
if(typeof msg !== 'string') throw 'Parameter message required of string type !';
// do the rest below
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.