Skipping multiple elements in a FOR loop, Javascript

断了今生、忘了曾经 提交于 2019-12-25 03:42:53

问题


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


回答1:


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.




回答2:


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




回答3:


Another method:

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



回答4:


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>


来源:https://stackoverflow.com/questions/30092638/skipping-multiple-elements-in-a-for-loop-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!