3
for char, index in 'some string'
    if condition
        index += 2

I have a for loop, where I'm looping over a string and when certain condition is met, I want to skip some number of characters after the current one. In JavaScript, I would do index += 2 and it would work, but for some unknown reason, CoffeeScript compiler compiles this code into JS for loop, that uses _i variable to keep the real index and only assigns the current value to index, which means that by changing the value of index, I'm not really changing the pointer.

I know I could do this using while loop, but I just keep thinking that there must be a way to do this using for loop. Am I right, or should I just stick to the while loop?

Here is the compiled JS code:

var char, index, _i, _len, _ref;

_ref = 'some string';
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
  char = _ref[index];
  if (condition) {
    index += 2;
  }
}
someName
  • 33
  • 3

1 Answers1

0

Have a look at: CoffeeScript for loop get iterator var

You can't change the real index of a for loop in CoffeeScript, AFAIK. You'd have to use a while loop instead.

Community
  • 1
  • 1
Pierre Wahlgren
  • 875
  • 7
  • 15