0
我有以下的代码,明显的作品,但我相当肯定存在的CoffeeScript表达这种更简洁的方式:的CoffeeScript - 数组初始化
todos = []
for i in [1..10]
todos.push App.store.find App.Todo, i
我有以下的代码,明显的作品,但我相当肯定存在的CoffeeScript表达这种更简洁的方式:的CoffeeScript - 数组初始化
todos = []
for i in [1..10]
todos.push App.store.find App.Todo, i
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);
}
括号改变什么的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))。 –
聪明。谢谢你的澄清! –