我的咖啡腳本這部分代碼,我想不出它如何與三元如果還是像這樣簡化..的CoffeeScript有助於簡化if語句
if options.tracks?
@collection.add(options.tracks, {at: length+1, dest:options.dest})
else
@collection.add(options, {at: length+1, dest:options.dest})
對不起,愚蠢的問題..
我的咖啡腳本這部分代碼,我想不出它如何與三元如果還是像這樣簡化..的CoffeeScript有助於簡化if語句
if options.tracks?
@collection.add(options.tracks, {at: length+1, dest:options.dest})
else
@collection.add(options, {at: length+1, dest:options.dest})
對不起,愚蠢的問題..
CoffeeScript中沒有容易tenary操作,但你可以使用具有說,如果這將產生任一分支
@collection.add((if options.tracks then options.tracks else options),
{at: length+1, dest:options.dest})
的最後一個表達式。我不會那樣寫,因爲它會造成很多視覺噪音,難以閱讀。最好做
tracks = if options.tracks then options.tracks else options
@collection.add(tracks, {at: length+1, dest:options.dest})
甚至更好
tracks = options.tracks || options
@collection.add(tracks, {at: length+1, dest:options.dest})
使用existential operator將產生相同的行爲,你的代碼:
@collection.add(options.tracks ? options, {at: length + 1, dest: options.dest})
我個人擺脫一些括號/括號也可以使用單獨的變量作爲第一個參數......但這更多關於個人偏好:
tracks = options.tracks ? options
@collection.add tracks, at: length + 1, dest: options.dest
謝謝,最後我會用) – Feanor 2013-02-21 14:34:29