栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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参数功能解决了此问题。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号