cod*_*rer 6 javascript named-parameters default-parameters
我是来自Python背景的JavaScript的新手.在Python中,参数可以作为键和值传递:
def printinfo( name, age = 35 ):
print "Name: ", name
print "Age ", age
return;
Run Code Online (Sandbox Code Playgroud)
然后可以这样调用该函数:
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Run Code Online (Sandbox Code Playgroud)
这些参数可以在JavaScript函数中传递吗?
我希望能够传递一个或多个参数.例如一个JavaScript函数:
function plotChart(data, xlabel, ylabel, chart_type="l"){
...
}
Run Code Online (Sandbox Code Playgroud)
我希望能够只传递数据和图表类型,标签是可选的,例如:
plotChart(data, chart_type="pie")
Run Code Online (Sandbox Code Playgroud)
这可以用JavaScript吗?
Sam*_*Sam 13
执行此操作的一种好方法是为所有参数使用对象.就像是:
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
}
Run Code Online (Sandbox Code Playgroud)
然后当调用该函数时:
plotChart({
data: 'some data',
xlabel: 'some xlabel',
ylabel: 'some ylabel',
chart_type: '5' // This is optional
});
Run Code Online (Sandbox Code Playgroud)
一种方法是检查参数值是否为undefined
,如果是,则分配一个值.
function plotChart(data, xlabel, ylabel, chart_type) {
if (typeof chart_type === 'undefined') {
chart_type = 'l';
}
}
Run Code Online (Sandbox Code Playgroud)
此外,EcmaScript 2016(ES6)还提供默认参数.由于某些浏览器尚不支持此功能,您可以使用诸如babel之类的转换器将代码转换为ES5.
为了使它像你的python示例一样工作,你必须传递一个包含值而不是单个参数的对象.
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);
}
Run Code Online (Sandbox Code Playgroud)
用法示例
plotChart({
xlabel: 'my label',
chart_type: 'pie'
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19110 次 |
最近记录: |