2012-09-07 48 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 !!!