我仍然試圖學習CoffeeScript,所以即時通訊只是詢問如何以更簡單的方式編寫此代碼。檢查具有特定屬性值的對象是否存在於一個數組中
for member in draft.members
if member.email is emailAddress then throw new Meteor.Error 500, "Cannot add member twice"
我仍然試圖學習CoffeeScript,所以即時通訊只是詢問如何以更簡單的方式編寫此代碼。檢查具有特定屬性值的對象是否存在於一個數組中
for member in draft.members
if member.email is emailAddress then throw new Meteor.Error 500, "Cannot add member twice"
第一步是使它可讀:
for member in draft.members
if member.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice'
我們可以if
-expression使用when
消除:
for member in draft.members when member.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice'
請不要寫可怕的長隊。請記住if
-表達式可以跨越多行。
對於一個完整的選擇,你可以,如果你使用Underscore.js或jQuery的消除for
-expression。下面是使用Underscore.js(如果你喜歡的jQuery,見$.grep
)爲例:
if _.find(draft.members, (m) -> m.email is emailAddress)
throw new Meteor.Error 500, 'Cannot add member twice'
海事組織,for
-expression與when
是最可讀的。
您還可以使用Array#some
,這會導致很簡單的JS,並且不需要外部庫:)
emailAlreadyUsed = draft.members.some (m) -> m.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice' if emailAlreadyUsed
謝謝,我同意'換when'是最可讀的一個,而正是我在尋找。謝謝。 – Snidd 2013-04-20 13:13:57