【发布时间】:2012-11-09 16:54:09
【问题描述】:
说明
我有一个传递参数options 的函数。此参数可以是 object、array 或 string。根据参数是什么,会决定做什么。
更新:我忘了提,options 必须始终以相同结构的对象结束(换句话说,它必须始终设置默认值)。
我只想定义一次默认值,因此像你们中的一些人建议的那样使用过程 if 语句不是我的首选解决方案,但如有必要,我会使用它。
我不想这样做(如果可能的话):
function foo(options){
switch(typeof options){
case 'string':
// do something etc
break;
// etc
}
}
示例
如果参数是一个对象,则扩展它以设置默认值,如下所示:
function foo(options){
// Extend the options to apply default values
var options = $.extend({
bar: 'none',
baz: []
},options);
}
如果参数是字符串,则将options.bar 设置为等于字符串并扩展默认值(类似这样):
function foo(options){
// Set the bar property to equal the supplied string
var options = {
bar: options
};
// Extend the options to apply default values
options = $.extend({
baz: []
},options);
}
如果参数是一个数组,则将options.baz 设置为等于该数组,并扩展默认值(类似这样):
function foo(options){
// Set the baz property to equal the supplied array
var options = {
baz: options
};
// Extend the options to apply default values
options = $.extend({
bar: 'none'
},options);
}
问题
如此有效,我希望能够提供任何格式的参数,并且该函数将从提供的内容构建相同的options 对象。如果没有提供这些值,那么它们会使用它们的默认值。
对不起,这个太不清楚了,很难解释。
附加示例
我 (jQuery) 可以演示的另一种潜在方法是查看像 animate() 这样的函数。请注意,您可以提供:
.animate( properties [, duration] [, easing] [, complete] )
或
.animate( properties, options )
这个额外的例子并不完全是我希望达到的,但它是正确的
【问题讨论】:
标签: javascript jquery parameters parameter-passing sinemacula