在 FOR 循环中跳过多个元素,Javascript

Skipping multiple elements in a FOR loop, Javascript

我想使用 javascript 函数将一些文件内容传递到我的服务器。在文件中,有很多空行,或者包含无用文本的行。到目前为止,我将每一行都作为存储在数组中的字符串读取。

然后我如何跳过多行(例如第 24、25、36、42、125 行等)遍历该内容。我可以将这些元素 ID 放入数组中并告诉我的 for 循环 运行除了这些之外的每个元素?

谢谢

你不能告诉你的 for 循环遍历所有,而是跳过某些元素。它基本上只会在任何方向(简化)计数,直到满足某个标准。

但是,您可以在循环中放置一个 if 来检查特定条件,如果条件满足,则选择什么都不做。例如:

(以下为伪代码,注意输入错误)

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

continue 关键字基本上告诉 for 循环 "jump over" 当前迭代的剩余部分并继续下一个值。

isUselessLine 函数是您必须自己实现的东西,在某种程度上,如果具有给定行号的行对您无用,则它 returns 为真。

你可以使用这样的东西

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

或者你可以有另一个数组变量,它获得了需要从 array1

中删除的所有项目

另一种方法:

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

你可以试试这个,它不是很优雅,但肯定会成功

<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>

如果你有很多索引要跳过,这取决于数组的元素,你可以编写一个函数,returns 为该数组中的每个索引跳过的元素数(或 returns 1, 如果不需要跳过):

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 ;
}

你的情况:

                               // 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)