简体   繁体   English

函数中可变数量的参数

[英]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.

相关问题 JavaScript 可变数量的函数参数 - JavaScript variable number of arguments to function 是否可以向 JavaScript 函数发送可变数量的参数? - Is it possible to send a variable number of arguments to a JavaScript function? 如何在JavaScript函数中使用可变数量的参数 - How to use a variable number of arguments in a JavaScript function 使用可变数量的输入 arguments 编写 function - Writing a function with variable number of input arguments Javascript:修改一个函数,打印出可递归的变量数量的参数? - Javascript: modifying a function which prints out variable number of arguments to be recursive? 具有可变数量/类型参数的函数的 TypeScript 声明文件 - TypeScript declaration file for function with variable number/type of arguments 如何在 JSDoc 中使用 Function 类型注释 object 类型,该类型具有可变数量的 arguments? - How to annotate an object with Function type that has variable number of arguments in JSDoc? 带有可变数量参数的Javascript函数-更改其值-然后返回 - Javascript function that takes variable number of arguments - changes their value - and then returns them 在javascript函数参数列表中传递可变数量的参数 - Passing Variable Number of arguments in javascript function argument-list 使函数接受可变数量的参数或数组中的值 - Make function accept both variable number of arguments, or values in array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM