简体   繁体   中英

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.

What some popular libraries (eg jQuery) that support variable types of arguments do is that they examine the arguments and then swap values accordingly:

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)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM