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

j8yoct9x  于 2023-01-19  发布在  Java
关注(0)|答案(5)|浏览(131)

我有一些文件内容想用javascript函数传递到服务器上,文件中有很多空行,或者是一些无用的文本,到目前为止,我把每一行都读成了一个存储在数组中的字符串。
然后,我如何跳过多行内容(如第24、25、36、42、125行等)来循环该内容。我是否可以将这些元素ID放入一个数组中,并告诉我的for循环在除这些元素之外的每个元素上运行?
谢谢

wpcxdonn

wpcxdonn1#

你不能告诉你的for循环去迭代所有的元素,但是跳过某些元素。它基本上只会在任何方向上计数(简化),直到某个条件被满足。
然而,你可以在你的循环中放置一个if来检查某些条件,并且如果条件满足,你可以选择不做任何事情。例如:
(下面是伪代码,注意键入错误)

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

continue关键字基本上告诉for循环“跳过”当前迭代的剩余部分并继续下一个值。
isUselessLine函数是您必须自己实现的,在某种程度上,如果具有给定行号的行对您无用,它将返回true。

3zwjbxry

3zwjbxry2#

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

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

pzfprimi3#

你可以用这个

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

或者,您可以使用另一个数组变量,该变量获取需要从array1中删除的所有项

kqlmhetl

kqlmhetl4#

另一种方法:

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

lhcgjxsq5#

如果你有很多索引要跳过,并且这取决于数组的元素,你可以写一个函数,返回数组中每个索引要跳过的元素数(或者返回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)

相关问题