Index variable (_i) in for loops?

前端 未结 2 1066
清歌不尽
清歌不尽 2021-01-19 16:11

Take a look at this simple code:

eat = (x) -> console.log \"nom\", x

# dog only eats every second cat
feast = (cats) -> eat cat for cat in cats when _         


        
2条回答
  •  臣服心动
    2021-01-19 17:13

    No need to guess, or make assumptions, about what Coffeescript does. Just look at the compiled Javascript. From the 'Try Coffeescript' tab:

    feast = (cats) -> eat cat for cat in cats when _i % 2 == 0
    

    produces

    feast = function(cats) {
      var cat, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = cats.length; _i < _len; _i++) {
        cat = cats[_i];
        if (_i % 2 === 0) {
          _results.push(eat(cat));
        }
      }
      return _results;
    };
    

    ...

    feast = (cats) -> eat cat for cat, index in cats when index % 2 == 0
    

    produces nearly the identical JS, differing only in that index is used along with or in place of _i.

    feast = function(cats) {
      var cat, index, _i, _len, _results;
      _results = [];
      for (index = _i = 0, _len = cats.length; _i < _len; index = ++_i) {
        cat = cats[index];
        if (index % 2 === 0) {
          _results.push(eat(cat));
        }
      }
      return _results;
    };
    

    Both work, but index makes your intentions clearer to humans (including your future self). And as others have argued, it is good programming practice to avoid use of undocumented implementation features - unless you really need them. And if you are doing something funny, document it.

提交回复
热议问题