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

问题描述 投票:0回答:6

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

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

谢谢

javascript arrays for-loop skip
6个回答
5
投票

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

但是,您可以在循环中放入 if 来检查某些条件,并在满足条件时选择不执行任何操作。例如:

(下面是伪代码,谨防打字错误)

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

continue 关键字基本上告诉 for 循环“跳过”当前迭代的其余部分并继续下一个值。

isUselessLine 函数是你必须自己实现的函数,在某种程度上,如果具有给定行号的行对你来说没有用,它会返回 true。


1
投票

你可以试试这个,虽然不太优雅,但绝对能达到目的

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

0
投票

你可以使用这样的东西

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

或者您可以有另一个数组变量,其中包含需要从中删除的所有项目

array1


0
投票

另一种方法:

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

0
投票

如果您有许多要跳过的索引,并且这取决于数组的元素,您可以编写一个函数,返回该数组中每个索引要跳过的元素数量(如果不需要跳过,则返回 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)

0
投票

如果您想跳过当前迭代 - 使用“继续”

如果您想跳过下一次迭代,例如 1 次或更多,您可以增加当前索引,因此下一次迭代从该索引开始,而不是下一个。

有一些抽象的例子,假设我们需要迭代数字数组,只有当当前数字小于 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
}
© www.soinside.com 2019 - 2024. All rights reserved.