"Splats"在CoffeeScript教程中的含义是什么?

int*_*tar 113 javascript coffeescript

看看这个CoffeeScript教程:http://jashkenas.github.com/coffee-script/

我不太清楚Splats的用途.这是什么建筑?它来自哪里(历史)

Tre*_*ham 198

术语"splat运算符"来自Ruby,其中*字符(有时称为"splat" - 参见术语文件条目)用于指示参数列表中的条目应"吸收"参数列表.

CoffeeScript中采用Ruby的风格泼溅很早(见第16期),但道格拉斯Crockford的建议下,语法是从改变*xx...几个星期之后(见第45期).尽管如此,CoffeeScripters仍然将语法称为"splat"或"splat运算符".

至于它们实际上做了什么,splats切割arguments对象的方式使得splatted参数成为所有"额外"参数的数组.最微不足道的例子是

(args...) ->
Run Code Online (Sandbox Code Playgroud)

在这种情况下,args将只是一个数组副本arguments.Splatted参数可以在标准参数之前,之后或之间进行:

(first, rest...) ->
(rest..., last) ->
(first, rest..., last) ->
Run Code Online (Sandbox Code Playgroud)

在前两种情况下,如果函数接收0-1参数,rest则将为空数组.在最后一种情况下,函数需要接收超过2个参数rest才能非空.

由于JavaScript不允许具有相同名称的函数的多个签名(C和Java的方式),因此splats可以节省大量时间来处理不同数量的参数.

  • 类似于C#[`params`](http://msdn.microsoft.com/en-us/library/w5zay9db.aspx)关键字. (2认同)

kep*_*pla 13

如果你知道python,args...大致相似*args,因为它允许你将函数参数视为列表

例如:

concat = (args...) -> args.join(', ')
concat('hello', 'world') == 'hello, world'
concat('ready', 'set', 'go!') == 'ready, set, go!'
Run Code Online (Sandbox Code Playgroud)

它也适用于装饰品:

[first, rest...] = [1, 2, 3, 4]
first == 1
rest == [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)


Jef*_*ter 6

Splats是...var-args运算符的使用术语(带有可变数量参数的函数).