是否可以根据传递的参数数量告诉函数应为其参数赋予什么名称?像这样:
function soSwag(swagLevel, swagStart, swagDuration || swagStart, swagStop){}
最佳答案
一些支持可变类型参数的流行库(例如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)
}
}