const arr = 1 2 3 4 5;function delayedForEacharr callback arrforEachitem index = setTimeout = callbackitem; index + 1 1000; ;delayedForEacharr item = consolelogitem;;怎么判断循环是否走完
可以在循环内部设置一个计数器,每次循环结束时计数器加一,然后在最后一个循环结束后判断计数器是否等于数组的长度,如果相等则说明循环已经走完。
以下是修改后的代码示例:
const arr = [1, 2, 3, 4, 5];
function delayedForEach(arr, callback) {
let count = 0; // 计数器
arr.forEach((item, index) => {
setTimeout(() => {
callback(item);
count++; // 每次循环结束计数器加一
if (count === arr.length) {
console.log('循环已走完');
}
}, (index + 1) * 1000);
});
}
delayedForEach(arr, (item) => {
console.log(item);
});
运行以上代码,当循环走完时会在控制台输出"循环已走完"
原文地址: https://www.cveoy.top/t/topic/iRxv 著作权归作者所有。请勿转载和采集!