2012-09-07 131 views
0

我是CoffeeScript的新手,所以也许我的问题没有建设性。如果是这样,我很抱歉。无论如何,问题在于写作功能。我尝试了2种方法,但变量无法正常工作。我应该如何写这个?带参数的函数定义

1路: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 [ '富']

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 ... 

谢谢你的好意。

回答

1

我借这个机会,更不用说其他一些细微:

您与arg...第一次尝试不起作用,因为...语法(称为splat)将余下的参数,并把他们在阵列arg

的改进到您的默认参数是:

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

    arg.base * arg.height/2 

?=使用existential operator构造物,并arg.base ?= 1将分配给1当且仅当arg.basearg.basenullundefined

但它变得更好! CoffeeScript中有destructuring assignment的支持,所以你可以写:

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

    base * height/2 

如果你愿意,你可以使用CoffeeScript中的默认参数是这样的:

triangle = ({base, height} = {base: 1, height: 2}) -> 
    base * height/2 

但是,这将工作,如果你想成为能够指定只有baseheight,即如果你称它为triangle(base: 3),heightundefined,所以可能不是你想要的。

0

对不起,我找到了答案。我应该使用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 !!!