How to pass the value 'undefined' to a function with multiple parameters?

前端 未结 12 2211
滥情空心
滥情空心 2020-12-14 14:26

I want to pass the value of \'undefined\' on a multiple parameter function but without omitting the parameter.

What do I mean with \"without omitting the paramet

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 14:40

    Just to give an examples on what @dbrin was explaining, and @alphapilgrim might have wished to check.

    simpleFunction({params1:12, params2:"abc"}); //use expected arguments
    simpleFunction({params2:"abc"}); //use only one
    simpleFunction({params2:"abc", params1:12, iDoNotExist:"I will not be included"}); //use expected arguments in any order
    simpleFunction(); //ignore arguments and uses defaults
    simpleFunction(2123); //ignores non object arguments 
    
    function simpleFunction(someParams){
      var myParams = {
        params1:null,
        params2:"cde" //default value for second parameter
      };
      simpleExtend(myParams, someParams);
      
      console.log(myParams);
    
    }
    
    
    //to include in your utilities
    function simpleExtend(currentParams, newParams){
      
      if(typeof currentParams !== "undefined" && typeof newParams !== "undefined"){
        Object.keys(newParams).forEach(function(key){
       
          if(typeof currentParams[key] !== "undefined"){
            currentParams[key] = newParams[key];    
          }
    
        });
     
      
      }
      
     
    
    }

提交回复
热议问题