Coffeescript 带参数的函数定义

Coffeescript 带参数的函数定义,coffeescript,Coffeescript,我是咖啡脚本的新手,所以我的问题可能不是建设性的。如果是这样,我很抱歉。无论如何,问题是写函数。我尝试了以下两种方法,但变量不起作用。我该怎么写 第一条路:arg.foo triangle = (arg...) -> if arg.base == undefined then arg.base = 1; if arg.height == undefined then arg.height = 1; arg.base * arg.height / 2 documen

我是咖啡脚本的新手,所以我的问题可能不是建设性的。如果是这样,我很抱歉。无论如何,问题是写函数。我尝试了以下两种方法,但变量不起作用。我该怎么写

第一条路:arg.foo

triangle = (arg...) ->
    if arg.base == undefined then arg.base = 1;
    if arg.height == undefined then arg.height = 1;
    arg.base * arg.height / 2

document.writeln triangle
    base:8
    height:5 # => return 0.5 ...
第二种方式:arg['foo']

triangle = (arg...) ->
    if arg['base'] == undefined then arg['base'] = 1;
    if arg['height'] == undefined then arg['height'] = 1;
    arg['base'] * arg['height'] / 2

document.writeln triangle
    base:8
    height:5 # => return 0.5 ...

谢谢你的好意。

很抱歉我找到了答案。我应该使用
arg
而不是
arg…

triangle = (arg) ->
    if arg.base == undefined then arg.base = 1;
    if arg.height == undefined then arg.height = 1;
    arg.base * arg.height / 2

document.writeln triangle
    base:8
    height:5 # => return 20 !!!

我要借此机会提及其他一些细节:

第一次尝试使用
arg…
无效,因为
..
语法(称为a)将获取剩余的参数并将它们放入数组
arg

对默认参数的改进是:

triangle = (arg) ->
    arg.base ?= 1
    arg.height ?= 1

    arg.base * arg.height / 2
构造
?=
正在使用,并且
arg.base?=1
1
分配给
arg.base
iff
arg.base
null
未定义

但是它变得更好了!Coffeescript支持,因此您可以编写:

triangle = ({base, height}) ->
    base ?= 1
    height ?= 1

    base * height / 2
如果愿意,可以使用Coffeescript的默认参数,如下所示:

triangle = ({base, height} = {base: 1, height: 2}) ->
    base * height / 2
但是,如果您想只指定
基准
高度
,也就是说,如果您将其称为
三角形(基准:3)
高度
将是
未定义的
,因此可能不是您想要的