我还在努力学习 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"
您也可以使用Array#some
,这会产生非常简单的 JS 并且不需要外部库 :)
emailAlreadyUsed = draft.members.some (m) -> m.email is emailAddress
throw new Meteor.Error 500, 'Cannot add member twice' if emailAlreadyUsed
第一步是让它可读:
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
- 表达式可以跨越多行。
至于完整的替代方案,for
如果您使用 Underscore.js 或 jQuery,则可以消除 - 表达式。下面是一个使用 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
最易读。