gpt4 book ai didi

javascript - JS 错误 : "undefined is not an object (evaluating ' dataText[i]. 长度')"

转载 作者:行者123 更新时间:2023-12-01 01:31:47 27 4
gpt4 key购买 nike

尽管这段代码按预期工作,即打印文本,但第 32 行出现控制台错误,内容为:“undefined 不是对象(评估 'dataText[i].length')”

有什么想法吗?

document.addEventListener('DOMContentLoaded',function(event){
// array with texts to type in typewriter
var dataText = [ "Hi", "it's Acephala", "Shipping is free for you today",];

// type one text in the typwriter
// keeps calling itself until the text is finished
function typeWriter(text, i, fnCallback) {
// chekc if text isn't finished yet
if (i < (text.length)) {
// add next character to h1
document.querySelector("h1animation").innerHTML = text.substring(0, i+1) +'<spananimation aria-hidden="true"></spananimation>';

// wait for a while and call this function again for next character || BK: Speed of text writing
setTimeout(function() {
typeWriter(text, i + 1, fnCallback)
}, 100);
}
// text finished, call callback if there is a callback function
else if (typeof fnCallback == 'function') {
// call callback after timeout
setTimeout(fnCallback, 700);
}
}
// start a typewriter animation for a text in the dataText array
function StartTextAnimation(i) {
if (typeof dataText[i] == 'undefined'){
setTimeout(function() {
StartTextAnimation(0);
}, 20000);
}
// check if dataText[i] exists
if (i < dataText[i].length) {
// text exists! start typewriter animation
typeWriter(dataText[i], 0, function(){
// after callback (and whole text has been animated), start next text
StartTextAnimation(i + 1);
});
}
}
// start the text animation
StartTextAnimation(0);
});

最佳答案

您的代码执行以下操作:

if (typeof dataText[i] == 'undefined'){
...
}
if (i < dataText[i].length) {
...
}

这意味着i < dataText[i].length即使 dataText[i] 也会被评估是 undefined 。添加 return第一个结尾处的声明if阻止或使用 else if (i < dataText[i].length) {

<小时/>

除此之外,我相信支票实际上应该是 i < dataText.length 。比较 dataText[i] 的长度似乎不太合理至i .

如果您进行了该更改,则不需要首先提到的更改。

但是,在这种情况下,我宁愿在回调内部进行检查,这意味着 StartTextAnimation总是收到有效的索引:

function StartTextAnimation(i) {
typeWriter(dataText[i], 0, function(){
// after callback (and whole text has been animated), start next text
if (i === dataText.length - 1) {
setTimeout(function() {
StartTextAnimation(0);
}, 20000);
} else {
StartTextAnimation(i + 1);
}
});
}

关于javascript - JS 错误 : "undefined is not an object (evaluating ' dataText[i]. 长度')",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53218008/

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