简体   繁体   English

获取Javascript函数中可变数量的参数

[英]Get variable number of parameters in Javascript function

I'm parsing an XML document with JS, changing to lower case every first letter of the tags names. 我正在用JS解析XML文档,将标签名称的每个首字母更改为小写。 IE <MyTagName></MyTagName> will become <myTagName></myTagName> , very simple and everything works fine. IE <MyTagName></MyTagName>将变为<myTagName></myTagName> ,非常简单,并且一切正常。 I'm using a regex to find all the tags and replacing the name with the camel version, like this: 我正在使用正则表达式查找所有标签,并用骆驼版本替换名称,如下所示:

regex = /(<)(\/){0,1}([A-Z]*)(\/){0,1}(>)/ig;

result = result.replace(regex, function(s, m0, m1, m2, m3, m4){
    return m0 + (m1 ? m1 : "") + camelNotation(m2) + (m3 ? m3 : "") + m4;
});

My question is: is there a way to get some of the parameters in the anonymous function which is the second argument of my replace function in a more dynamic way, like an array? 我的问题是:有没有办法以更动态的方式(例如数组)获取匿名函数中的某些参数,该函数是我的replace函数的第二个参数? Something like 就像是

result = result.replace(regex, function(s, param[]){
    return param[0] + (param[1]? param[1] : "") + camelNotation(param[2]) + (param[3] ? param[3] : "") + param[4];
});

I may use arguments[i] , but I would like to know if I can customize my parameters in the function signature. 我可以使用arguments[i] ,但是我想知道是否可以在函数签名中自定义参数。

Thank you 谢谢

I often use the following simple higher-order function: 我经常使用以下简单的高阶函数:

splat = function(fun, thisp) {
    return function() { return fun.call(thisp, [].slice.call(arguments)) }
}

eg 例如

"a1b2c3d4e5f6".replace(/(\D)(\d)/g, splat(function(a) {
    return a[1].toUpperCase() + (++a[2]);
}))

You can grab the arguments inside the body of the function like so: 您可以像下面这样在函数体内获取参数:

result = result.replace(regex, function(s, /*params...*/){
  // get real array without the first argument
  var params = [].slice.call(arguments, 1);
  ...
});

I may use arguments[i], but I would like to know if I can customize my parameters in the function signature. 我可能使用arguments [i],但是我想知道是否可以在函数签名中自定义参数。

You can use arguments or get the arguments you want into an array, but other than that there's no alternative syntax (yet, it's coming soon). 您可以使用arguments或将所需的参数放入数组中,但是除此之外,没有其他语法(但是,即将推出)。 The convention for "rest params" is to annotate them as a comment. “其余参数”的约定是将它们注释为注释。

You can use a forwarding function to package up the arguments into an array: 您可以使用转发功能将参数打包到一个数组中:

result.replace(regex, function(s) {
    return realFunction(s, Array.prototype.slice.call(arguments, 1));
});

where realFunction has the signature function(s, params) (it can of course be defined and called inline if you prefer). 其中, realFunction具有签名function(s, params)当然,可以根据需要定义并调用内联函数)。 See the documentation on arguments for info on how this works. 请参阅arguments文档以获取有关其工作原理的信息。

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

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