JavaScript 中的 Splat 运算符,相当于 Python 中的 *args 和 **kwargs?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17380315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splat operators in JavaScript, equivalent to *args and **kwargs in Python?
提问by Games Brainiac
I use Python a lot, and I am just quickly learning JavaScript right now (or should I say re-learning). So, I wanted to ask, what is the equivalent of *args
and **kwargs
in JavaScript?
我经常使用 Python,而且我现在正在快速学习 JavaScript(或者我应该说重新学习)。所以,我想问一下,在 JavaScript中*args
和的等价物是**kwargs
什么?
采纳答案by NPE
The closest idiom for *args
would be
最接近的成语*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 */
}
taking advantage of the fact that Function.length
is the number of arguments given in the function definition.
利用Function.length
函数定义中给出的参数数量这一事实。
You could package this up in a little helper routine like
你可以把它打包成一个小助手程序,比如
function get_star_args (func, args) {
return Array.prototype.slice.call (args, func.length);
}
and then do
然后做
function func (a, b /*, *args*/) {
var star_args = get_star_args (func, arguments);
/* now star_args[0] is the first undeclared argument */
}
If you're in the mood for syntactic sugar, write a function which transforms one function into another one which is called with required and optional arguments, and passes the required arguments along, with any additional optional arguments as an array in final position:
如果您想使用语法糖,请编写一个函数,将一个函数转换为另一个使用必需和可选参数调用的函数,并将必需参数连同任何其他可选参数一起传递为最终位置的数组:
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);
};
}
Use this as follows:
使用方法如下:
// 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);
Then again, you could just skip all this mumbo jumbo if you are willing to ask the caller to pass the optional arguments as an array to start with:
再说一次,如果您愿意要求调用者将可选参数作为数组传递以开始,您可以跳过所有这些笨拙的巨无霸:
myfunc (1, 2, [3]);
There is really no analogous solution for **kwargs
, since JS has no keyword arguments. Instead, just ask the caller to pass the optional arguments in as an object:
确实没有类似的解决方案**kwargs
,因为 JS 没有关键字参数。相反,只需要求调用者将可选参数作为对象传入:
function myfunc (a, b, starstar_kwargs) {
console.log (a, b, starstar_kwargs.x);
}
myfunc (1, 2, {x:3});
ES6 Update
ES6 更新
For completeness, let me add that ES6 solves this problem with the rest parameter feature. See Javascript - '...' meaning
为了完整起见,让我补充一点,ES6 使用 rest 参数功能解决了这个问题。参见Javascript - '...' 的意思
回答by NPE
The nearest equivalent is the arguments
pseudo-array.
最接近的等价物是arguments
伪数组。
回答by Luke W
I found a good solution here: http://readystate4.com/2008/08/17/javascript-argument-unpacking-converting-an-array-into-a-list-of-arguments/
我在这里找到了一个很好的解决方案:http: //readystate4.com/2008/08/17/javascript-argument-unpacking-converting-an-array-into-a-list-of-arguments/
Basically, use function.apply(obj, [args])
instead of function.call
. apply takes an array as the 2nd arg and 'splats' it for you.
基本上,使用function.apply(obj, [args])
代替function.call
. apply 将一个数组作为第二个参数并为您“splats”它。
回答by Cameron Martin
ECMAScript 6 will have rest parameterswhich do the same thing as the splat operator.
ECMAScript 6 将具有与 splat 运算符执行相同操作的其余参数。
回答by Helio Santos
ES6 added a spread operator to JavaScript.
ES6 向 JavaScript 添加了扩展运算符。
function choose(choice, ...availableChoices) {
return availableChoices[choice];
}
choose(2, "one", "two", "three", "four");
// returns "three"
回答by N Djel Okoye
For those who might be slightly lost about *args and **kwargs magic variables read http://book.pythontips.com/en/latest/args_and_kwargs.html
对于那些可能对 *args 和 **kwargs 魔法变量有点迷茫的人,请阅读http://book.pythontips.com/en/latest/args_and_kwargs.html
Summary: *args and **kwargs are just conventional ways of writing the magic variables. You could just say * and ** or *var and **vars. That said lets talk about the JavaScript equivalent in 2019.
总结: *args 和 **kwargs 只是编写魔法变量的常规方法。你可以只说 * 和 ** 或 *var 和 **vars。话虽如此,让我们谈谈 2019 年的 JavaScript 等价物。
*args in python represents a JavaScript Array e.g. ["one", "two", "three"] to pass that into a python function you would just define the function as def function_name(*args): meaning this function accepts "arrays" or "list if you wish" to call that you would simply use function function(["one", "two", "three"]):
*args 在 python 中表示一个 JavaScript 数组,例如 ["one", "two", "three"] 将它传递给一个 python 函数,你只需将函数定义为 def function_name(*args):意味着这个函数接受“数组”或“如果您愿意,请列出”来调用您只需使用函数 function(["one", "two", "three"]):
same thing in JavaScript can be done by using :
在 JavaScript 中,同样的事情可以通过使用来完成:
function(x,y,z){
...
}
let *args = ["one", "two", "three"];
function(...*args)
**or more dynamically as**
function(inputs<T>:Array){
for(index in inputs){
console.log(inputs[index]);
}
}
let *args = ["one", "two", "three"];
function(*args)
Have a look at https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831
看看https://codeburst.io/a-simple-guide-to-destructuring-and-es6-spread-operator-e02212af5831
**kwargs on the other hand represent just an array of key value pairs(objects) that's it. Thus **kwargs e.g is [{"length": 1, "height": 2}, {"length":3, "height": 4}]
**kwargs 另一方面只代表一个键值对(对象)数组,就是这样。因此 **kwargs 例如是 [{"length": 1, "height": 2}, {"length":3, "height": 4}]
in python to define a function accepting array of objects you just say def function_name(**kwargs): then to call that you can do function_name( [{"length": 1, "height": 2}, {"length":3, "height": 4}]):
在python中定义一个接受对象数组的函数,你只需说 def function_name(**kwargs): 然后调用你可以做 function_name( [{"length": 1, "height": 2}, {"length": 3、“高度”:4}]):
similarly in JS
在 JS 中类似
const **kwargs = [{"length": 1, "height": 2}, {"length":3, "height": 4}]
function(obj1, obj2){
...
}
function(...**kwargs);
**or more dynamically as:**
const **kwargs = [{"length": 1, "height": 2}, {"length":3, "height": 4}]
function(obj){
for(const [key, value] of Object.entries(obj)){
console.log(key, ": ", value)
}
function(**kwargs);