【发布时间】:2023-03-14 21:48:01
【问题描述】:
下面是一个带有命名参数的常规函数:
function who(name, age, isMale, weight)
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who('Jack', 30, true, 90); //this is OK.
我想要实现的是;你是否按顺序传递参数;该函数应该产生类似的结果(如果不同的话):
who('Jack', 30, true, 90); //should produce the same result with the regular function
who(30, 90, true, 'Jack'); //should produce the same result
who(true, 30, 'Jack', 90); //should produce the same result
这使您能够以任何顺序传递参数列表,但仍将映射到逻辑顺序。到目前为止,我的方法是这样的:
function who()
{
var name = getStringInArgs(arguments, 0); //gets first string in arguments
var isMale = getBooleanInArgs(arguments, 0); //gets first boolean in arguments
var age = getNumberInArgs(arguments, 0); //gets first number in arguments
var weight = getNumberInArgs(arguments, 1); //gets second number in arguments
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
这里有个小问题; getStringInArgs() 和 getNumberInArgs() 等函数每次都会遍历所有参数,以在指定位置按类型查找 arg。我只能遍历 args 一次并为位置保留标志,但是我必须在 who() 函数中执行此操作。
您认为这种方法合乎逻辑并且是唯一的方法吗?有更好的方法吗?
编辑 1: 上面的代码确实有效。我只是想知道是否有更好的方法。
编辑 2:您可能想知道这是否有必要或是否有意义。主要原因是:我正在编写一个 jQuery 函数,它将特定样式添加到 DOM 元素。我希望此函数将其参数视为速记 CSS 值。
例子:
border: 1px solid red;
border: solid 1px red; /*will produce the same*/
所以;这是迄今为止的真实和最终代码:
(function($){
function getArgument(args, type, occurrence, defaultValue)
{
if (args.length == 0) return defaultValue;
var count = 0;
for(var i = 0; i < args.length; i++)
{
if (typeof args[i] === type)
{
if (count == occurrence) { return args[i]; }
else { count++; }
}
}
return defaultValue;
}
$.fn.shadow = function()
{
var blur = getArgument(arguments, 'number', 0, 3);
var hLength = getArgument(arguments, 'number', 1, 0);
var vLength = getArgument(arguments, 'number', 2, 0);
var color = getArgument(arguments, 'string', 0, '#000');
var inset = getArgument(arguments, 'boolean', 0, false);
var strInset = inset ? 'inset ' : '';
var sValue = strInset + hLength + 'px ' + vLength + 'px ' + blur + 'px ' + color;
var style = {
'-moz-box-shadow': sValue,
'-webkit-box-shadow': sValue,
'box-shadow': sValue
};
return this.each(function()
{
$(this).css(style);
});
}
})(jQuery);
用法:
$('.dropShadow').shadow(true, 3, 3, 5, '#FF0000');
$('.dropShadow').shadow(3, 3, 5, '#FF0000', true);
$('.dropShadow').shadow();
【问题讨论】:
-
我认为虽然你有两个数字类型的参数,但你不能这样做。如果每个参数都有不同的类型,这是可能的
-
@Mohsen,这确实有效。多个数字类型参数没有问题。事实上,相同类型的参数是有序的。请查看编辑。
标签: javascript jquery function parameters arguments