2012-10-20 100 views
0

我有以下的代碼,明顯的作品,但我相當肯定存在的CoffeeScript表達這種更簡潔的方式:的CoffeeScript - 數組初始化

todos = [] 

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

回答

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); 
} 
+0

括號改變什麼的CoffeeScript認爲循環體是,它不在於是否將評估一個數組(考慮一下[這個循環(HTTP ://coffeescript.org/#try:f%20%3D%20-%3E%20c%20%3D%20b%20for%20b%20in%20a%0A)彙編成)。如果編譯器檢測到數組不會被使用(如[this循環](http://coffeescript.org/#try:f%20%3D%20-%3E%0A %20%20%20%20℃%20%3D%20B%20for%20B%20英寸%20A%0A%20%20%20%2011%0A))。 –

+0

聰明。謝謝你的澄清! –