如何在javascript中检测循环的结束
How to detect the end of the loop in javascript
使用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);
相关文章:
- 循环结束/推送到数组之前在页面上呈现EJS
- 如何在javascript中循环结束后执行语句
- addclass循环结束时调用函数
- Node/Express - 如何等到 For 循环结束再使用 JSON 进行响应
- Javascript-在while循环结束后仅显示数组中的最后一个值
- 循环结束后重新启动jQuery.ech()
- 当for循环结束时,Javascript执行一个操作
- 当JS循环结束时,jQuery hide()
- 等待循环结束并执行第二个函数
- 在for循环结束时调用promise
- 在重复循环结束处修改SVG animateTransform
- 如何等到jquery效果的循环结束后再执行函数
- 在每次迭代时向DOM添加一个元素,而不是在循环结束时添加全部元素
- 在循环结束前执行的循环内的AJAX调用
- 如何在循环结束后发送函数的结果
- Javascript for循环直到循环结束才执行函数,然后迭代函数n次
- 使用for循环结束时给定的值重新启动JavaScript for循环
- 变量在循环结束时不递增
- clearartimeout只在循环结束时起作用
- 在每个循环结束时执行一些操作