Search code examples
javascriptarraysfor-loopcontinue

Continue has no effect in for loop?


I'm a beginner trying to solve this kata:

In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

"a" = 1, "b" = 2, etc.

My solution seems to be working until it encounters a whitespace in the given string, then it includes those as an element of the positions array. I know this is probably fixable by just filtering out the whitespaces but I would really like to know why my code isn't working.

function alphabetPosition(text) {
  const alphabet="abcdefghijklmnopqrstuvwxyz".split('');
  const letters = text.toLowerCase().split('');
  let positions =[];
  for (i=0; i<letters.length; i++){
    if (!(alphabet.includes(letters[i]))){
      continue;
      }
      positions[i]=(alphabet.indexOf(letters[i])+1);          
    }
  return (positions.join(' '));  
}

I thought by using continue, it should just skip over the whitespaces within the letters array but the continue keyword seems to not have any effect. I have tried to look up the correct use of continue and really can't find my mistake. Any help would be much appreciated, thanks in advance!


Solution

  • The continue command does skip the execution of the following commands in the loop, but the loop counter i is still increased. When you use positions with indexes, the gap in the indexes that results from that can be seen when using join.

    Use push() to build up the positions array instead of indexes to prevent gaps.

    for (i=0; i<letters.length; i++){
        if (!(alphabet.includes(letters[i]))){
            continue;
        }
        positions.push(alphabet.indexOf(letters[i])+1);          
    }