最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Skipping multiple elements in a FOR loop, Javascript - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question asked May 7, 2015 at 5:32 Leon SmithLeon Smith 514 silver badges9 bronze badges 2
  • You can use the continue statement for this purpose. I can post an example if you want – Harigovind R Commented May 7, 2015 at 5:43
  • for skipping in loops you cloud use continue.Also these numbers are random. or fixed for different files. – sachin.ph Commented May 7, 2015 at 5:46
Add a ment  | 

6 Answers 6

Reset to default 5

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.

You can try this its not much elegent but will suerly do the trick

<html>
<body>

<p>A loop which will skip the step where i = 3,4,6,9.</p>

<p id="demo"></p>

<script>
    var text = "";
    var num = [3,4,6,9];
    var i;

    for (i = 0; i < 10; i++) {
        var a = num.indexOf(i);
        if (a>=0) { 
            continue; 
        }
        text += "The number is " + i + "<br>";
    }

    document.getElementById("demo").innerHTML = text;
</script>

</body>

You could use something like this

    var i = 0, len = array1.length;
    for (; i < len; i++) {
        if (i == 24 || i == 25) {
            array1.splice(i, 1);
        }
    }

Or you can have an another array variable which got all the items that need to be removed from array1

Another method:

var lines = fileContents.match(/[^\r\n]+/g).filter(function(str,index,arr){
    return !(str=="") && uselessLines.indexOf(index+1)<0;
});

If you have many indices to skip, and this depends on the elements of the array, you could write a function that returns the number of elements to skip over for each index in that array (or returns 1, if no skipping required):

for ( let i = 0; 
      i < array.length;
      i += calcNumberOfIndicesToSkip( array, i )){
   // do stuff to the elements that aren't 
   // automatically skipped
}

function calcNumberOfIndicesToSkip( array, i ){
  // logic to determine number of elements to skip
  // (this may be irregular)
  return numberOfElementsToSkip ;
}

In your case:

                               // skip the next index (i+1)?
for ( let i=0; i<array.length; i+=skipThisIndex(i+1) ){ 
    // do stuff 
}

function skipThisIndex(i){
    const indicesToSkip = [ 24, 25, 36, 42, 125 ];
    return 1 + indicesToSkip.includes(i);
}

// returns 1 if i is not within indicesToSkip 
// (there will be no skipping)
//      => (equivalent to i++; normal iteration)
// or returns 1 + true (ie: 2) if i is in indicesToSkip
//      => (index will be skipped)

If you want to skip the current iteration - use 'continue'

If you want to skip the next iterations, like 1 or more, you can increment the current index, so the next iteration starts from that index, instead of the next.

Here is an abstract example, assume we need iterate over arrays of number, only if the current number is less than 5:

for (let i = 0, i < arr.length; i++) {

  if (arr[i + 1] > 5 ) {
    // skip next iteration
    i++;
  }

  if (arr[i] > 5) {
    // skip current iteration
    continue;
  }

  // ...rest logic
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论