[英]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:
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. 假设我想要像这样调用 function:
plot(lines, xlabel="Project",
ylabel="Investor",
xfmt="%", xscale=100, yfmt="%.", yscale=100)
我想在 function 定义中获得“xlable”、“Project”、“ylabel”、“Investor”、“xfmt”、“%”等(可能还有更多参数)。
我该如何写'情节' function def?
function plot( data, kwargs={},...restArguments){
}
然后您可以通过 restArguments 数组获取值,但您无法获取 arguments 的名称。
由于 JavaScript 不支持命名 arguments,因此您最好的选择是使用下面描述的字典方法来处理变量参数。
你可以:
arguments
object 。 这适用于每个版本的 ECMAScript。arguments
方法。请注意,如果不进行一些重构,您将无法使用方法 2 和 3。
以object为参数,使用属性为实际参数。 这样,您可以(某种程度上)通过它们的标识符来引用它们。
这将使:
function aFunc(aVar, anotherVar, aThirdVar) {
console.log(aVar, anotherVar, aThirdVar);
}
对此:
function aFunc(data) {
console.log(data.aVar, data.anotherVar, data.aThirdVar);
}
新的 function 可以这样调用:
aFunc({aVar: 5, anotherVar: 10, aThirdVar: 20}); // Works
// -- or --
// Note the un-ordered properties
aFunc({aThirdVar: 20, aVar: 5, anotherVar: 10}); // Also works
但是,这会带来以下问题:
data.var ||= 'fallback-value';
.使用这种方法的优点是:
arguments
object 由于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).
使用它,您可以使用 function 的参数以及访问 function 的参数列表中未列出的任何其他参数。
采用可变数量 arguments 的函数应具有名为 var_args 的最后一个参数。 您可能不会在代码中引用 var_args; 使用 arguments 阵列。
请注意,仅仅因为谷歌这样做并不意味着这是一个人应该编码的方式。 它只是在处理 Google 代码时如何编码的指南(。)。
以下是遵循 Google 风格指南的示例:
function aFunc(first, second, var_args) {
console.log(first, second, arguments[2], arguments[3]);
}
aFunc(5, 10, 20); // => '5 10 20 undefined'
ES6 中引入了 Rest 参数语法和箭头函数 (lambda) 表达式。
由于建议使用此方法而不是使用arguments
object,因此在决定使用两者中的哪一个时,应尝试实施此方法,因为访问其余参数更直观,它也适用于箭头函数表达式,并且 Z55276C10D84E1DF7713B441E 参数为一个实际的数组。
因为 Rest 参数是一个实际的数组,所以可以使用扩展语法以及Array
继承的任何功能,这与arguments
object 不同。
这是一个类似于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.