Skipping Multiple Elements In A For Loop, Javascript
Solution 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.
Solution 2:
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><pid="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>
Solution 3:
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
Solution 4:
Another method:
var lines = fileContents.match(/[^\r\n]+/g).filter(function(str,index,arr){
return !(str=="") && uselessLines.indexOf(index+1)<0;
});
Solution 5:
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
}
functioncalcNumberOfIndicesToSkip(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
}
functionskipThisIndex(i){
const indicesToSkip = [ 24, 25, 36, 42, 125 ];
return1 + 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)
Post a Comment for "Skipping Multiple Elements In A For Loop, Javascript"