Index variable (_i) for loops?

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 _i % 2 == 0

feast ["tabby cat"
       "siamese cat"
       "norwegian forest cat"
       "feral cat"
       "american bobtail"
       "manx"]

$ coffee a.coffee 
nom tabby cat
nom norwegian forest cat
nom american bobtail

The variable seems to _ibe the current index. Is this a sign, error, or NaN? I have not heard anyone else talking about this, so I wonder if there is any reason why I should not use it in my code?

+4
source share
2 answers

TL; DR-again; CoffeeScript author just told me I'm right : Do not use _i.

14:29 <jashkenas> You shouldn't use internal variables. 
...
14:42 <meagar> I was hoping something more deeply involved in the language would be able to put some authority behind that opinion 
14:43 <meagar> ... I was basically hoping for an authoritative "don't do that" 
14:44 <jashkenas> you just got it ;) 
14:44 <jashkenas> for item, index in list -- there your reference to the index. 

TL;DR; , . , .

" " ; :

for x in [1, 2, 3] when _i % 2 == 0
  console.log "#{_i} -> #{x}"

for x,i in [1, 2, 3] when i % 2 == 0
  console.log "#{i} -> #{x}"

, NaN?

; undefined. , _i , JavaScript.

_i, , _i . , . _i, ; _j _k ..

, , JavaSript. , for value,key in array:

array = ['a', 'b', 'c']

console.log(index) for item, index in array # 0, 1, 2

, :

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

, Coffeescript. Javascript. "Try Coffeescript":

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

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

JS, , index _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;
};

, index ( ). , , , - . - , .

+2

All Articles