gpt4 book ai didi

javascript - 递归函数错误在第二次运行时跳过数组中的第一个元素

转载 作者:行者123 更新时间:2023-12-02 23:03:50 25 4
gpt4 key购买 nike

我有这个函数可以打印数组中的每个字母。这是 jsFiddle 的链接:

https://jsfiddle.net/yaroslav_cherednikov/ypbuhmqv/71/

它在第一次运行时运行良好,但在第二次运行时跳过数组中的第一个元素

    var a = ["Saab", "Volvo", "BMW", "renault"];
var d = document.getElementById('out');
var c = document.getElementById("cursor");
window.count = 0;
window.word_count = 0;

setTimeout(function () {
c.style.visibility = 'visible';
function aLoop() {
setTimeout(function () {
if(window.count < a.length){
return lettersPrint(a[window.count]);
}
}, 50);
}
function lettersPrint(word) {
if (window.word_count < word.length) {
setTimeout(function () {
d.innerHTML += word[window.word_count];
window.word_count++;
return lettersPrint(word);
}, 100);
}
else if( window.count < (a.length - 1) ){
setTimeout(function () {
d.classList.add("selected");
}, 1000);
setTimeout(function () {
window.count++;
word_count = 0;
d.classList.remove("selected");
d.innerHTML = '';
return aLoop();

}, 2000);
}
else{
window.count = 0;
aLoop();
}
}
aLoop();

}, 1000);
.typer-txt {
font-size: 2vw;
color: #378bd8;
display: inline-block;
}
#cursor {
float: right;
color: #b9b9b9;
animation: pulse 0.5s infinite;
visibility: hidden;
}
#out {
display: inline;
}
.selected {
background-color: #378bd8;
color: white;
}
@-webkit-keyframes h1-slide-up {
0% {top:100px; opacity: 0;}
100% {top:0px; opacity: 1;}
}

@keyframes pulse {
0% {
opacity: 0
}

100% {
opacity: 1;
}
}
<div class="typer-txt remove" id="typer-txt"><span id="cursor">|</span><div id="out" class=""></div></div>

这是我第一次处理递归函数,所以我可能弄乱了一些东西。任何帮助将不胜感激。

最佳答案

当您到达最后一个单词时,您不会重置字数统计。我已经更新了您的代码并将突出显示和删除部分重构为自己的函数

    var a = ["Saab", "Volvo", "BMW", "renault"];
var d = document.getElementById('out');
var c = document.getElementById("cursor");
window.count = 0;
window.word_count = 0;

setTimeout(function () {
c.style.visibility = 'visible';
function aLoop() {
setTimeout(function () {
debugger;
if(window.count < a.length){
return lettersPrint(a[window.count]);
}
}, 50);
}
function highlightAndErase(winCount) {
setTimeout(function () {
d.classList.add("selected");
}, 1000);
setTimeout(function () {
window.count = winCount
word_count = 0;
d.classList.remove("selected");
d.innerHTML = '';
return aLoop();

}, 2000);

}
function lettersPrint(word) {
// previously was being missed after the last word due to the word_count not being reset
if (window.word_count < word.length) {
setTimeout(function () {
d.innerHTML += word[window.word_count];
window.word_count++;
return lettersPrint(word);
}, 100);
}
else if( window.count < (a.length - 1) ){
highlightAndErase(++window.count)
}
else{
// previously was not resetting the word_count var
highlightAndErase(0)
}
}
aLoop();

}, 1000);

关于javascript - 递归函数错误在第二次运行时跳过数组中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57678994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com