Onu*_*rım 3 javascript parameters jquery arguments function
下面是一个带有命名参数的常规函数:
function who(name, age, isMale, weight)
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who('Jack', 30, true, 90); //this is OK.
Run Code Online (Sandbox Code Playgroud)
我想要的是; 是否按顺序传递参数; 该函数应该产生类似的结果(如果不相同):
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
Run Code Online (Sandbox Code Playgroud)
这使您可以按任何顺序传递参数列表,但仍将映射到逻辑顺序.我到目前为止的做法是这样的:
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.');
}
Run Code Online (Sandbox Code Playgroud)
这里有一点问题; 功能,如getStringInArgs()
和getNumberInArgs()
通过所有的参数,每次去找到类型ARG在指定的位置.我可以只遍历args一次并保持位置的标志,但是我必须在who()函数内执行它.
你认为这种方法是合乎逻辑的吗?有没有更好的方法呢?
编辑1:上面的代码实际上有效.我只是想知道是否有更好的方法.
编辑2:您可能想知道这是否必要或是否有意义.主要原因是:我正在编写一个jQuery函数,它为DOM元素添加了一个特定的样式.我希望此函数将其参数视为速记CSS值.
例:
border: 1px solid red;
border: solid 1px red; /*will produce the same*/
Run Code Online (Sandbox Code Playgroud)
所以; 这是现在的真实和最终代码:
(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);
Run Code Online (Sandbox Code Playgroud)
用法:
$('.dropShadow').shadow(true, 3, 3, 5, '#FF0000');
$('.dropShadow').shadow(3, 3, 5, '#FF0000', true);
$('.dropShadow').shadow();
Run Code Online (Sandbox Code Playgroud)
我发现将来使用对象更直接,更不容易出错:
var person = {
name: 'Jack',
age: 30,
isMale: true,
weight: 90
};
who(person);
function who(person){
alert(person.name +
' (' + (person.isMale ? 'male' : 'female') + '), ' +
person.age + ' years old, ' +
person.weight + ' kg.');
}
Run Code Online (Sandbox Code Playgroud)
这样,当您多年后回来时,您不必查找年龄是第一个,第二个还是第五个数字,并且更能描述您想要实现的目标.
归档时间: |
|
查看次数: |
776 次 |
最近记录: |