Handling optional parameters in javascript

前端 未结 12 930
无人共我
无人共我 2020-11-28 19:19

I have a static javascript function that can take 1, 2 or 3 parameters:

function getData(id, parameters, callback) //parameters (associative array) and callb         


        
12条回答
  •  生来不讨喜
    2020-11-28 20:10

    I recommend you to use ArgueJS.

    You can just type your function this way:

    function getData(){
      arguments = __({id: String, parameters: [Object], callback: [Function]})
    
      // and now access your arguments by arguments.id,
      //          arguments.parameters and arguments.callback
    }
    

    I considered by your examples that you want your id parameter to be a string, right? Now, getData is requiring a String id and is accepting the optionals Object parameters and Function callback. All the use cases you posted will work as expected.

提交回复
热议问题