JavaScript function with optional parameters [duplicate]

不打扰是莪最后的温柔 提交于 2020-01-10 14:58:53

问题


I'm new to JavaScript coming from Python background. In Python parameters can be passed as key and value as such:

def printinfo( name, age = 35 ):
   print "Name: ", name
   print "Age ", age
   return;

Then the function could be called as such:

printinfo( age=50, name="miki" )
printinfo( name="miki" )

Can such parameters be passing in JavaScript functions?

I want to be able to pass one or more parameter. For example a JavaScript function as such:

function plotChart(data, xlabel, ylabel, chart_type="l"){
    ...
} 

I want to be able to pass only data and chart type and labels are optional such as :

plotChart(data, chart_type="pie")

Is this possible with JavaScript?


回答1:


A good way to do this would be to use an object for all of the arguments. Something like:

function plotChart(options) {
  // Set defaults
  options.chart_type = options.chart_type || '1';

  // Check if each required option is set
  // Whatever is used by the data
}

Then when the function is called:

plotChart({
  data: 'some data',
  xlabel: 'some xlabel',
  ylabel: 'some ylabel',
  chart_type: '5' // This is optional
});



回答2:


One way is to check if the parameter value is undefined and if so then assign a value.

function plotChart(data, xlabel, ylabel, chart_type) {
  if (typeof chart_type === 'undefined') {
     chart_type = 'l';
  }
} 

Also EcmaScript 2016 (ES6) offers Default Parameters. Since some browser don't yet support this feature you can use a transpiler such as babel to convert the code to ES5.

To make it work like in your python example you would have to pass an object containing the values instead of individual parameters.

function plotChart(options) {
    var data = options.data;
    var xlabel = options.xlabel;
    var ylabel = options.ylabel;
    var chart_type = (typeof options.chart_type === 'undefined' ? 'l' : options.chart_type);
}

Example usage

plotChart({
  xlabel: 'my label',
  chart_type: 'pie'
});



回答3:


There's a ton of answers for this already, but I havn't seen what I considered to be the simplest solution to this.

var myFunc = function(param1) {
    var someData = param1 || "defaultValue";
}



回答4:


You can check if parameters are defined and hard code that into your functions.

e.g.

 var preDefined = function(param) { 
    if(param === undefined) { 
        param = preDefinedValue
     }
     /* Rest of code goes here */
 }

ETA:

ES6 was allows for default parameter values (was unaware of this when I posted the answer).

Link



来源:https://stackoverflow.com/questions/34388641/javascript-function-with-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!