JavaScript中的Splat运算符是否等效于Python中的* args和** kwargs?

JavaScript中的Splat运算符是否等效于Python中的* args和** kwargs?,第1张

JavaScript中的Splat运算符是否等效于Python中的* args和** kwargs?

最接近的成语

*args

function func (a, b ) {    var star_args = Array.prototype.slice.call (arguments, func.length);    }

利用

Function.length
函数定义中给定的参数个数这一事实。

您可以将其打包到一些帮助程序中,例如

function get_star_args (func, args) {    return Array.prototype.slice.call (args, func.length);}

然后做

function func (a, b ) {    var star_args = get_star_args (func, arguments);    }

如果您想使用语法糖,请编写一个函数,该函数将一个函数转换为另一个函数,该函数使用必需和可选参数调用,并将必需参数以及任何其他可选参数作为数组传递到最终位置:

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 nvar 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);    };}

如下使用:

// original functionfunction myfunc (a, b, star_args) {     console.log (a, b, star_args[0]); // will display 1, 2, 3}// argsify itvar argsified_myfunc = argsify (myfunc);// call argsified functionargsified_myfunc (1, 2, 3);

再说一次,如果您愿意让调用者将可选参数作为数组开头,则可以跳过所有这些巨型菜单:

myfunc (1, 2, [3]);

确实没有类似的解决方案

**kwargs
,因为JS没有关键字参数。相反,只需要求调用方将可选参数作为对象传递即可:

function myfunc (a, b, starstar_kwargs) {    console.log (a, b, starstar_kwargs.x);}myfunc (1, 2, {x:3});
ES6更新

为了完整起见,让我补充一点,ES6使用rest参数功能解决了此问题。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5639664.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存