如何在javascript中检测循环的结束

How to detect the end of the loop in javascript

本文关键字:循环 结束 检测 javascript      更新时间:2023-09-26

使用for(var i = 0; i < str.length; i++),我可以很容易地检测循环是否在末尾。

但我怎么能知道我是在用for还是for每个。

for(var i = 0; i < str.length; i++) {
    if(End of for) //Do something if the end of the loop
}

如何在javascript中找到for的最后一个循环?

for(var i = 0; i < str.length; i++) {        
    if(i== str.length-1) { 
    //Do something if the end of the loop    
    }
}

使用forin

 for (var item in str) {
      if(str[str.length-1] == item) {
        //Do something if the end of the loop
      }
    }

const str = "I am a 24 letter string!";
for (let i = 0; i < str.length; i++) {
  if (i + 1 === str.length) {
    console.log('Last loop:', i + 1)
  }
}

for (var item in str) {
    if(str[parseInt(item)+1] === undefined) {
        //Do something if the end of the loop
    }
}

 for(var i = 0; i < arr.length; i++){
     if(i == (arr.length - 1)){
      //do you stuff
     }
 }

只需将最后一件事从循环中分离出来。注意在条件中使用str.length - 1

//from the beginning up to but not including the last index
for(var i = 0; i < str.length - 1; i++) {
    console.log(i)
}
//from the last index only
console.log(str.length - 1)

forEach循环中,必须对数组进行线性迭代,因此需要一些条件逻辑和计数器来检测最后一个元素。我发现下面的内容更难阅读,效率也更低,尤其是如果你真的以这种方式使用匿名函数的话。此外,由于需要一个计数器,使用我分享的第一种方法更有意义。

var i = 0;
array.forEach(function(i) {
    if(i === str.length - 1) {
        //do the last thing
    } else {
        //do all the other things
    }
    i++;
});

您可以使用console.log()。如果将其放入循环中,您将能够在控制台中查看每个结果。

console.log(i);