且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何测试是否为函数提供了参数?

更新时间:2022-01-25 07:23:59

这是一种非常频繁的模式。

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 "".