javascriptarraysfor-loopskip

Skipping multiple elements in a FOR loop, Javascript


I have some file contents I'd like to pass on to my server using a javascript function. In the file, there are many empty lines, or those which contain useless text. So far I read every line in as a string stored in an array.

How do I then loop through that content skipping multiple lines such as lines 24,25, 36, 42, 125 etc. Can I put these element id's into an array and tell my for loop to run on every element except these?

Thanks


Solution

  • you can't tell your for loop to iterate all, but skip certain elements. it will basically just count in any direction (simplified) until a certain critera has been met.

    you can however put an if inside your loop to check for certain conditions, and chose to do nothing, if the condition is met. e.g.:

    (pseudo code below, beware of typing errors)

    for(var line=0; line < fileContents.length; line++) { 
        if(isUselessLine(line)) { 
            continue; 
        }
        // process that line
    }
    

    the continue keyword basically tells the for loop to "jump over" the rest of the current iteration and continue with the next value.

    The isUselessLine function is something you'll have to implement yourself, in a way, that it returns true, if the line with the given linenumber is useless for you.