[英]Variable number of arguments in a function
Is it possible to tell a function what names it should give to its arguments, based on the number of arguments passed? 是否有可能根据传递的参数数量告诉函数它应该给它的参数赋予什么名称? Like this:
像这样:
function soSwag(swagLevel, swagStart, swagDuration || swagStart, swagStop){}
Not to my knowledge. 据我所知。 However, you can just pass in an object with the data you want.
但是,您只需传入包含所需数据的对象即可。
soSwag({
swagStart: 10,
swagStop: 100
});
However, it might be cleaner to simply pass null
into that first parameter. 但是,将
null
传递给第一个参数可能更简洁。
What some popular libraries (eg jQuery) that support variable types of arguments do is that they examine the arguments and then swap values accordingly: 支持变量类型的参数的一些流行的库(例如jQuery)做的是它们检查参数然后相应地交换值:
function soSwag(swagLevel, swagStart, swagDuration) {
if (arguments.length === 2) {
var swagStop = swagStart; // 2nd arg becomes swagStop
swagStart = swagLevel; // first arg becomes swagStart
// code here that uses swagStart and swagStop
// as called like soSwag(swagStart, swagStop)
} else {
// code here that uses swagLevel, swagStart, swagDuration
// as called like soSwag(swagLevel, swagStart, swagDuration)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.