简体   繁体   English

使用可变数量的输入 arguments 编写 function

[英]Writing a function with variable number of input arguments

I have a javascript function whose number of input arguments is not known ( has variable number of arguments) and it has also an input dictionary argument called "kwargs" argument which can have some other arguments as (key,value), like this: I have a javascript function whose number of input arguments is not known ( has variable number of arguments) and it has also an input dictionary argument called "kwargs" argument which can have some other arguments as (key,value), like this:

function plot( data, kwargs={}){
}

I want to get both the "name" and "value" of the arguments in the body of the function when I call the function with a number of arguments. I want to get both the "name" and "value" of the arguments in the body of the function when I call the function with a number of arguments. Suppose that I want to have a function call like this:假设我想要像这样调用 function:

plot(lines, xlabel="Project", 
        ylabel="Investor", 
        xfmt="%", xscale=100, yfmt="%.", yscale=100)

I want to gain "xlable", "Project", "ylabel", "Investor", "xfmt","%" and so on(maybe more arguments) in the function definition.我想在 function 定义中获得“xlable”、“Project”、“ylabel”、“Investor”、“xfmt”、“%”等(可能还有更多参数)。

How can I write 'plot' function def?我该如何写'情节' function def?

function plot( data, kwargs={},...restArguments){
                                                }

Then you can get the values by restArguments array but you cant get the name of the arguments.然后您可以通过 restArguments 数组获取值,但您无法获取 arguments 的名称。

Since JavaScript doesn't support named arguments, your best bet would be to use the dictionary-approach described below for the variable parameters.由于 JavaScript 不支持命名 arguments,因此您最好的选择是使用下面描述的字典方法来处理变量参数。

You can:你可以:

  1. Use a dictionary as an argument.使用字典作为参数。 That would allow you to access the "arguments" by their property-name.这将允许您通过其属性名称访问“参数”。
    However, that would require the caller to pass an object, which is potentially created every time the function is called, giving your program some addititonal overhead.但是,这将要求调用者传递一个 object,它可能会在每次调用 function 时创建,从而给您的程序带来一些额外的开销。
  2. Use the arguments object .使用arguments object This works for every version of ECMAScript.这适用于每个版本的 ECMAScript。
    However, you would have to access it with an offset equal to the amount of named parameters.但是,您必须使用等于命名参数数量的偏移量来访问它。
  3. Use the Rest Parameter-syntax .使用Rest 参数语法 This works since ES6 and is recommended over the arguments -approach.这从 ES6 开始有效,建议使用arguments方法。

Note that without some refactoring, you will not be able to use approach 2 and 3.请注意,如果不进行一些重构,您将无法使用方法 2 和 3。

Using a dicionary使用字典

Take an object as a parameter and take use properties as the actual parameters.以object为参数,使用属性为实际参数。 That way, you can (kind of) refer to them by their identifier.这样,您可以(某种程度上)通过它们的标识符来引用它们。

This would make this:这将使:

function aFunc(aVar, anotherVar, aThirdVar) {
  console.log(aVar, anotherVar, aThirdVar);
}

To this:对此:

function aFunc(data) {
  console.log(data.aVar, data.anotherVar, data.aThirdVar);
}

And the new function could be called like this:新的 function 可以这样调用:

aFunc({aVar: 5, anotherVar: 10, aThirdVar: 20}); // Works
// -- or --
// Note the un-ordered properties
aFunc({aThirdVar: 20, aVar: 5, anotherVar: 10}); // Also works

However, this comes with the following problems:但是,这会带来以下问题:

  • It isn't intuitive to how functions are called函数的调用方式并不直观
  • Defining fallback-values for properties has to be implemented in a non-native way.为属性定义回退值必须以非本地方式实现。
    One could achieve this by short-circuiting like this: data.var ||= 'fallback-value';可以通过这样的短路来实现这一点: data.var ||= 'fallback-value'; . .
  • IDEs cannot statically check your code for errors before execution IDE 无法在执行前静态检查您的代码是否存在错误
  • The parameter-list isn't helpful for the developer参数列表对开发人员没有帮助
  • Most significant: An actual object would have to be passed.最重要的是:必须通过实际的 object。 This is most likely created just for one call, which would give the programm unnecessary overhead when the function is called multiple times.这很可能是为一次调用创建的,当 function 被多次调用时,这会给程序带来不必要的开销。

The advantages of using this approach are:使用这种方法的优点是:

  • "Parameters" are defined as properties of an object. “参数”定义为 object 的属性。 This keeps the lexical scope clean(-er).这使词汇 scope 保持干净(-er)。
    However, this should not be a factor for deciding what approach to choose.但是,这不应成为决定选择哪种方法的因素。
  • Since properties of an object are (by default) enumerable, you can both get the name of the property as well as the value of it (this might be what you are aiming for).由于 object 的属性(默认情况下)是可枚举的,因此您既可以获得属性的名称,也可以获得它的值(这可能是您的目标)。

Using the arguments object使用arguments object

Since arguments is present in all versions of ECMAScript, I would recommend this approach when aiming for (quite a bit of) backwards-compatibility.由于arguments存在于所有版本的 ECMAScript 中,因此当目标是(相当多的)向后兼容性时,我会推荐这种方法。

arguments is present in any function execution context, meaning in both function declarations as well as function expressions , however not in arrow-function (lambda) expressions (added in ES6; for ES6 usage, using the Rest Parameter-syntax is recommended anyway). arguments is present in any function execution context, meaning in both function declarations as well as function expressions , however not in arrow-function (lambda) expressions (added in ES6; for ES6 usage, using the Rest Parameter-syntax is recommended anyway).

Using this, you can use the parameters of a function as well as access any further parameter not listed in the parameter-list of a function.使用它,您可以使用 function 的参数以及访问 function 的参数列表中未列出的任何其他参数。

Quoting from Google's JavaScript Style Guide :引用谷歌的 JavaScript 风格指南

Functions that take a variable number of arguments should have the last argument named var_args.采用可变数量 arguments 的函数应具有名为 var_args 的最后一个参数。 You may not refer to var_args in the code;您可能不会在代码中引用 var_args; use the arguments array.使用 arguments 阵列。

Note that just because Google does it this way doesn't mean that this is the way one should code.请注意,仅仅因为谷歌这样做并不意味着这是一个人应该编码方式。 It is just a guide(.) for how to code when working on code from Google.它只是在处理 Google 代码时如何编码的指南(。)。

Here is an example following Google's Style Guide:以下是遵循 Google 风格指南的示例:

function aFunc(first, second, var_args) {
  console.log(first, second, arguments[2], arguments[3]);
}

aFunc(5, 10, 20); // => '5 10 20 undefined'

Using the Rest Parameter-syntax使用 Rest 参数语法

Both the Rest Parameter-syntax as well as the arrow-function (lambda) expression were introduced in ES6. ES6 中引入了 Rest 参数语法和箭头函数 (lambda) 表达式。

Since this is recommended over using the arguments object, one should try to implement this approach when deciding which one of the two to use, because accessing the remaining parameters is more intuitive, it also works with arrow-function expressions, and the Rest Parameter is an actual array.由于建议使用此方法而不是使用arguments object,因此在决定使用两者中的哪一个时,应尝试实施方法,因为访问其余参数更直观,它也适用于箭头函数表达式,并且 Z55276C10D84E1DF7713B441E 参数为一个实际的数组。

Because the Rest Parameter is an actual array, one can use the Spread Syntax as well as any functionality inherited by Array , unlike the arguments object.因为 Rest 参数是一个实际的数组,所以可以使用扩展语法以及Array继承的任何功能,这与arguments object 不同。

Here is an example similar to the arguments object-approach, now using the Rest Parameter-syntax instead:这是一个类似于arguments对象方法的示例,现在使用 Rest 参数语法代替:

function aFunc(first, second, ...rest) {
  console.log(first, second, rest[0], rest[1]);
}

aFunc(5, 10, 20);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 函数中可变数量的参数 - Variable number of arguments in a function 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 编写一个将整数作为输入并将位数返回为二进制的函数 - Writing a function that takes an integer as input, and returns number of bits to binary 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
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM