What does "Splats" mean in the CoffeeScript tutorial?

Looking at this CoffeeScript tutorial : http://jashkenas.github.com/coffee-script/

I don't quite see what the Splats is for. What is this construction? Where does it come from (historically)

25269 次浏览

Splats 是对 var-args (带有可变数量参数的函数)使用 ...操作符的术语。

if you know python, args... roughly similar to *args, as it allows you to treat function parameters as list

例如:

concat = (args...) -> args.join(', ')
concat('hello', 'world') == 'hello, world'
concat('ready', 'set', 'go!') == 'ready, set, go!'

它也适用于分配任务:

[first, rest...] = [1, 2, 3, 4]
first == 1
rest == [2, 3, 4]

我认为它是 javascript 参数对象的语法糖。

这个想法可能来自 Ruby 的 splat operator *

术语“ splat 操作符”来自 Ruby,其中的 *字符(有时称为“ splat”ー参见 行话文件条目)用于指示参数列表中的一个条目应该“吸收”参数列表。

CoffeeScript adopted Ruby-style splats very early on (see 第十六期), but at Douglas Crockford's suggestion, the syntax was changed from *x to x... a couple of weeks later (see 第45期). Nevertheless, CoffeeScripters still refer to the syntax as the "splat" or "splat operator."

至于它们实际上做了什么,splats 将 arguments对象切割成这样一种方式,即 splatts 参数变成一个包含所有“额外”参数的数组。最简单的例子是

(args...) ->

In this case, args will simply be an array copy of arguments. Splatted arguments can come either before, after, or between standard arguments:

(first, rest...) ->
(rest..., last) ->
(first, rest..., last) ->

在前两种情况下,如果函数接收0-1个参数,则 rest将是一个空数组。在最后一种情况下,函数需要接收两个以上的参数才能使 rest为非空。

由于 JavaScript 不允许对同名函数使用多个签名(就像 C 和 Java 那样) ,因此在处理不同数量的参数时,splats 可以大大节省时间。