How to test if a parameter is provided to a function?

后端 未结 8 1056
不知归路
不知归路 2020-12-13 03:45

I was wondering, can you create a function with an optional parameter.

Example:

function parameterTest(test)
{
   if exists(test)
   {
     alert(\'t         


        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 04:06

    This is a very frequent pattern.

    You can test it using

    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) {
    

    Because you wouldn't be able to differentiate an unprovided value from false, 0 or "".

提交回复
热议问题