我还在尝试学习CoffeeScript,所以我只想问你如何以更简单的方式编写这段代码。
for member in draft.members
if member.email is emailAddress then throw new Meteor.Error 500, "Cannot add member twice"
答案 0 :(得分:3)
您也可以使用Array#some
,这会产生非常简单的JS并且不需要外部库:)
emailAlreadyUsed = draft.members.some (m) -> m.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice' if emailAlreadyUsed
答案 1 :(得分:2)
第一步是让它可读:
for member in draft.members
if member.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice'
我们可以使用if
消除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
- 表达式。以下是使用Underscore.js的示例(如果您更喜欢jQuery,请参阅$.grep
):
if _.find(draft.members, (m) -> m.email is emailAddress)
throw new Meteor.Error 500, 'Cannot add member twice'
IMO,for
- when
表达式最具可读性。