CoffeeScript 循环和推导式
你可以使用CoffeeScript将大多数的循环写成基于数组、对象或范围的推导式(comprehensions)。 推导式替代(编译为)for循环,并且可以使用可选的子句和数组索引值。 不同于for循环,数组的推导式是表达式,可以被返回和赋值。
CoffeeScript:编译成JS:
- # 吃午饭.
- eat food for food in ['toast', 'cheese', 'wine']
- # 精致的五道菜.
- courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
- menu i + 1, dish for dish, i in courses
- # 注重健康的一餐.
- foods = ['broccoli', 'spinach', 'chocolate']
- eat food for food in foods when food isnt 'chocolate'
- var courses, dish, food, foods, i, _i, _j, _k, _len, _len1, _len2, _ref;
- _ref = ['toast', 'cheese', 'wine'];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- food = _ref[_i];
- eat(food);
- }
- courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];
- for (i = _j = 0, _len1 = courses.length; _j < _len1; i = ++_j) {
- dish = courses[i];
- menu(i + 1, dish);
- }
- foods = ['broccoli', 'spinach', 'chocolate'];
- for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
- food = foods[_k];
- if (food !== 'chocolate') {
- eat(food);
- }
- }
推导式可以适用于其他一些使用循环的地方,例如each/forEach,
map,或者select/filter,例如:
shortNames = (name for name in list when name.length < 5)
如果你知道循环的开始与结束,或者希望以固定的跨度迭代,你可以在范围推导式中
指定开始与结束。
编译成JS:
- countdown = (num for num in [10..1])
- var countdown, num;
- countdown = (function() {
- var _i, _results;
- _results = [];
- for (num = _i = 10; _i >= 1; num = --_i) {
- _results.push(num);
- }
- return _results;
- })();
如果你希望仅迭代在当前对象中定义的属性,通过hasOwnProperty检查并
避免属性是继承来的,可以这样来写:
for own key, value of object
CoffeeScript仅提供了一种底层循环,即while循环。与JavaScript中的while 循环的主要区别是,在CoffeeScript中while可以作为表达式来使用, 而且可以返回一个数组,该数组包含每个迭代项的迭代结果。
CoffeeScript:编译成JS:
- # 经济 101
- if this.studyingEconomics
- buy() while supply > demand
- sell() until supply > demand
- # 摇篮曲
- num = 6
- lyrics = while num -= 1
- "#{num} little monkeys, jumping on the bed.
- One fell out and bumped his head."
- var lyrics, num;
- if (this.studyingEconomics) {
- while (supply > demand) {
- buy();
- }
- while (!(supply > demand)) {
- sell();
- }
- }
- num = 6;
- lyrics = (function() {
- var _results;
- _results = [];
- while (num -= 1) {
- _results.push("" + num + " little monkeys, jumping on the bed. One fell out and bumped his head.");
- }
- return _results;
- })();
为了更好的可读性,until关键字等同于while not, loop关键字 等同于while true。
使用 JavaScript 循环生成函数的时候, 经常会添加一个闭包来包裹代码, 这样做目的是为了循环的变量被保存起来, 而不是所有生成的函数搜去访问最后一个循环的变量. CoffeeScript 提供了一个 do 关键字, 用来直接调用跟在后边的函数, 并且传递需要的参数.
CoffeeScript:编译成JS:
- for filename in list
- do (filename) ->
- fs.readFile filename, (err, contents) ->
- compile filename, contents.toString()
- var filename, _fn, _i, _len;
- _fn = function(filename) {
- return fs.readFile(filename, function(err, contents) {
- return compile(filename, contents.toString());
- });
- };
- for (_i = 0, _len = list.length; _i < _len; _i++) {
- filename = list[_i];
- _fn(filename);
- }
转载本站内容时,请务必注明来自W3xue,违者必究。