具有可选参数的JavaScript函数 [英] JavaScript function with optional parameters
问题描述
我是来自Python背景的JavaScript新手。在Python中,参数可以这样作为键和值传递:
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" )
可以在JavaScript函数中传递这样的参数吗?
Can such parameters be passing in JavaScript functions?
我希望能够传递一个或多个参数。例如这样的JavaScript函数:
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")
JavaScript是否可能?
Is this possible with JavaScript?
推荐答案
<一个很好的方法是对所有参数使用一个对象。
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
}
然后在调用函数时:
plotChart({
data: 'some data',
xlabel: 'some xlabel',
ylabel: 'some ylabel',
chart_type: '5' // This is optional
});
这篇关于具有可选参数的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!