coffeescript - 数组初始化

时间:2012-10-20 07:16:10

标签: coffeescript

我有以下代码显然有效,但我相当有一种更简洁的方式在coffeescript中表达这一点:

  todos = []

  for i in [1..10]                                                                            
    todos.push App.store.find App.Todo, i 

1 个答案:

答案 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);
}