我有以下代码显然有效,但我相当有一种更简洁的方式在coffeescript中表达这一点:
todos = []
for i in [1..10]
todos.push App.store.find App.Todo, i
答案 0 :(得分:1)
todos = (App.store.find(App.Todo, i) for i in [1..10])
括号表示list comprehension,它将返回值收集到数组中并返回它。
考虑以下两个例子。括号括起来改变了Coffeescript解释循环的方式。
# With parentheses (list comprehension)
todos = (App.store.find(App.Todo, i) for i in [1..10])
# Without parentheses (plain old loop)
todos = App.store.find(App.Todo, i) for i in [1..10]
输出:
// With parentheses
todos = (function() {
var _i, _results;
_results = [];
for (i = _i = 1; _i <= 10; i = ++_i) {
_results.push(App.store.find(App.Todo, i));
}
return _results;
})();
// Without parentheses
for (i = _i = 1; _i <= 10; i = ++_i) {
todos = App.store.find(App.Todo, i);
}