我有这个逻辑来循环作为参数传递的值,并每秒打印一个字母


let sequenceI = 0;
function sequence(arr){
document.getElementsByTagName('P')[0].innerHTML += arr[sequenceI];
++sequenceI;  
setTimeout(() => sequence(arr), 150);
if (sequenceI > arr.length) {
document.getElementsByTagName('P')[0].innerHTML ="";
sequenceI = 0;
} 
}
sequence('Software Developer');

我有这个逻辑来循环作为参数传递的值,并每秒打印一个字母。当sequenceI变为18时,为什么不返回undefined?但它更倾向于再次启动循环

当sequenceI变为18时,为什么不返回undefined?但它更倾向于再次启动循环

语句arr[sequenceI](当sequenceI为18时(确实返回undefined。它无法在屏幕上显示为文本,因为您可以立即将文本重置为空字符串。

以下是当sequenceI为18 时发生的情况

// 'undefined' is added to the text on screen
document.getElementsByTagName('P')[0].innerHTML += arr[sequenceI];
// sequenceI goes from 18 to 19
++sequenceI;
// a callback is scheduled 150ms from now
setTimeout(() => sequence(arr), 150);
// the check is made and because 19 > 18 it resolves to true
if (sequenceI > arr.length) {
// the text is reset to an empty string
document.getElementsByTagName('P')[0].innerHTML ="";
// sequenceI is set to 0, and since there is a call scheduled 150ms from now,
// it will just restart the whole thing from the beginning (in 150ms) 
sequenceI = 0;
}

最新更新