Gam*_*iac 64 javascript python
我经常使用Python,而且我现在正在快速学习JavaScript(或者我应该说重新学习).所以,我想问,什么是相当于*args和**kwargs在JavaScript?
小智 38
最接近的成语*args是
function func (a, b /*, *args*/) {
var star_args = Array.prototype.slice.call (arguments, func.length);
/* now star_args[0] is the first undeclared argument */
}
Run Code Online (Sandbox Code Playgroud)
利用Function.length函数定义中给出的参数数量这一事实.
你可以把它打包成一个小帮手程序,比如
function get_star_args (func, args) {
return Array.prototype.slice.call (args, func.length);
}
Run Code Online (Sandbox Code Playgroud)
然后呢
function func (a, b /*, *args*/) {
var star_args = get_star_args (func, arguments);
/* now star_args[0] is the first undeclared argument */
}
Run Code Online (Sandbox Code Playgroud)
如果您想要语法糖,请编写一个函数,将一个函数转换为另一个函数,该函数使用必需和可选参数调用,并传递所需的参数,并将任何其他可选参数作为最终位置的数组:
function argsify(fn){
return function(){
var args_in = Array.prototype.slice.call (arguments); //args called with
var required = args_in.slice (0,fn.length-1); //take first n
var optional = args_in.slice (fn.length-1); //take remaining optional
var args_out = required; //args to call with
args_out.push (optional); //with optionals as array
return fn.apply (0, args_out);
};
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
// original function
function myfunc (a, b, star_args) {
console.log (a, b, star_args[0]); // will display 1, 2, 3
}
// argsify it
var argsified_myfunc = argsify (myfunc);
// call argsified function
argsified_myfunc (1, 2, 3);
Run Code Online (Sandbox Code Playgroud)
再说一次,如果你愿意让调用者将可选参数作为一个数组开始传递,你可以跳过所有这些mumbo jumbo:
myfunc (1, 2, [3]);
Run Code Online (Sandbox Code Playgroud)
实际上没有类似的解决方案**kwargs,因为JS没有关键字参数.相反,只要求调用者将可选参数作为对象传递:
function myfunc (a, b, starstar_kwargs) {
console.log (a, b, starstar_kwargs.x);
}
myfunc (1, 2, {x:3});
Run Code Online (Sandbox Code Playgroud)
为了完整起见,让我补充说ES6通过其余参数功能解决了这个问题.见http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html.
Hel*_*tos 27
ES6为JavaScript添加了一个扩展运算符.
function choose(choice, ...availableChoices) {
return availableChoices[choice];
}
choose(2, "one", "two", "three", "four");
// returns "three"
Run Code Online (Sandbox Code Playgroud)
Luk*_*e W 18
我在这里找到了一个很好的解决方案:http: //readystate4.com/2008/08/17/javascript-argument-unpacking-converting-an-array-into-a-list-of-arguments/
基本上,使用function.apply(obj, [args])而不是function.call.apply将数组作为第二个arg并为其"splats".
| 归档时间: |
|
| 查看次数: |
35070 次 |
| 最近记录: |