我不是在每个匹配值上调用一个函数,而是想获取值['broccoli', 'spinach']
的数组,但是我一直遇到编译器错误。有人可以解释一下我的误解吗?
# Health conscious meal. - This example is from http://coffeescript.org/#loops
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
# Failed Attempt #1 - Unexpected TERMINATOR
arr = for food in foods when food isnt 'chocolate'
# Failed Attempt #2 - Unexpected ')'
arr = (for food in foods when food isnt 'chocolate')
答案 0 :(得分:6)
您错过了理解应该返回的值(原始值为eat food
,但您希望未经修改返回food
。所以而不是:
for food in foods when food isnt 'chocolate'
你想:
food for food in foods when food isnt 'chocolate'
(虽然如果你的目标是现代JavaScript,那么使用像foods.filter (food) -> food isnt 'chocolate'
这样的东西可能会更具可读性。)