Scottie
Scottie

Reputation: 1051

Why CoffeeScript create a unexpected array for my loops

My CoffeeScript code:

myloop = () ->
  size = parseInt $('#size').val

  $('#result').css 'text-align', 'center'

  for i in [1..size] by 1
    for j in [1..i] by 1
      $('#result').append "<img src='alpha.jpg' />"
    $('#result').append "<br />"

Compile into Javascript:

// Generated by CoffeeScript 1.6.3
(function() {
  var myloop;

  myloop = function() {
    var i, j, size, _i, _j, _results;
    size = parseInt($('#size').val);
    $('#result').css('text-align', 'center')
    _results = [];
    for (i = _i = 1; _i <= size; i = _i += 1) {
      for (j = _j = 1; _j <= i; j = _j += 1) {
        $('#result').append("<img src='alpha.jpg' />");
      }
      _results.push($('#result').append("<br />"));
    }
    return _results;
  };

}).call(this);

As my expect that _result should not be generated.

It should be $('#result').append("<br />") instead.

How can I fixed this? Thx.

Upvotes: 1

Views: 86

Answers (1)

Blender
Blender

Reputation: 298582

Look at the docs:

Sometimes functions end with loops that are intended to run only for their side-effects. Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.

To "fix" your code, just add a return statement at the end of your function.

Upvotes: 1

Related Questions