如何在CoffeeScript中将理解结果收集到数组中?

时间:2012-02-02 17:54:28

标签: coffeescript list-comprehension

我不是在每个匹配值上调用一个函数,而是想获取值['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')

1 个答案:

答案 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'这样的东西可能会更具可读性。)