如何测试是否为函数提供了参数? [英] How to test if a parameter is provided to a function?
本文介绍了如何测试是否为函数提供了参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道,你能用可选参数创建一个函数。
I was wondering, can you create a function with an optional parameter.
示例:
function parameterTest(test)
{
if exists(test)
{
alert('the parameter exists...');
}
else
{
alert('The parameter doesn\'t exist...');
}
}
所以如果你打电话给 parameterTest ()
然后结果将是一条消息参数不存在......。如果你调用 parameterTest(true)
,那么它将返回参数存在...。
So if you call parameterTest()
then the result would be a message "The parameter doesn't exist...". And if you call parameterTest(true)
then it would return "the parameter exists...".
这可能吗?
推荐答案
这是一种非常频繁的模式。
This is a very frequent pattern.
您可以使用
function parameterTest(bool) {
if (bool !== undefined) {
然后你可以调用你的函数其中一种形式:
You can then call your function with one of those forms :
parameterTest();
parameterTest(someValue);
小心不要经常出现测试错误
Be careful not to make the frequent error of testing
if (!bool) {
因为你将无法区分未提供的值与 false
, 0
或。
Because you wouldn't be able to differentiate an unprovided value from false
, 0
or ""
.
这篇关于如何测试是否为函数提供了参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文