如何在coffeescript for循环中运行函数

时间:2013-04-27 09:43:40

标签: arrays for-loop coffeescript

我写这样的coffeescript:

split_typer_text = typer_text.split ''
test = (char) ->
  setTimeout (-> element.text(element.text() + char)), 100
test char for char in split_typer_text

但是coffeescript对此进行了反思:

test = function(char) {
    return setTimeout((function() {
      return element.text(element.text() + char);
    }), 100);
  };
  _results = [];
  for (_i = 0, _len = split_typer_text.length; _i < _len; _i++) {
    char = split_typer_text[_i];
    _results.push(test(char));
  }
  return _results;

我想要运行功能,不需要数组。 怎么办?

2 个答案:

答案 0 :(得分:0)

当我编译该源代码时,我得到了这个......

var char, split_typer_text, test, _i, _len;

split_typer_text = typer_text.split('');

test = function(char) {
  return setTimeout((function() {
    return element.text(element.text() + char);
  }), 100);
};

for (_i = 0, _len = split_typer_text.length; _i < _len; _i++) {
  char = split_typer_text[_i];
  test(char);
}

也许更新你的coffeescript ......

bash-3.2$ coffee --version
CoffeeScript version 1.6.2

答案 1 :(得分:0)

您正在运行测试功能,就在这里:

_results.push(test(char));
#-------------^^^^^^^^^^

Everything是CoffeeScript中的一个表达式,包含for循环。 for循环的结果是一个数组,因此编译的JavaScript中有_results数组和_results.push

在某些情况下,CoffeeScript编译器可以保证不会使用for循环的值,因此在编译时可以优化_results内容。例如,在这个CoffeeScript中:

f = ->
    i for i in [0..11]
    42

保证永远不会使用for循环值,因此JavaScript中没有数组:

var f;

f = function() {
  var i, _i;

  for (i = _i = 0; _i <= 11; i = ++_i) {
    i;
  }
  return 42;
};

Demo

但是,在这种情况下,for循环是函数的返回值,因此需要数组:

f = ->
    i for i in [0..11]

您将看到在JavaScript中填充的数组:

var f;

f = function() {
  var i, _i, _results;

  _results = [];
  for (i = _i = 0; _i <= 11; i = ++_i) {
    _results.push(i);
  }
  return _results;
};

Demo

如果您确定不想浪费时间使用数组,那么您必须告诉CoffeeScript不会使用该数组,如何执行此操作取决于上下文。例如,您可以添加一个空return来表示周围的函数不返回任何内容:

f = ->
    i for i in [0..11]
    return

你会得到这个:

var f;

f = function() {
  var i, _i;

  for (i = _i = 0; _i <= 11; i = ++_i) {
    i;
  }
};

Demo

相关问题