[英]Cannot read property 'length' of undefined - Error in JavaScript
我正在使用再現打字機效果的代碼在 html / css / js 中學習動畫。 一切正常,但我在控制台上不斷收到此錯誤:
**script.js:33 Uncaught TypeError: Cannot read property 'length' of undefined
at StartTextAnimation (script.js:33)
at script.js:37**
我嘗試了一些在谷歌上找到的解決方案,但沒有任何效果。 在我的 console.log(dataText) 中,我的數組中的每個字符串都正確執行。 錯誤出現在循環執行的那一刻。
這是我現在正在處理的代碼:
document.addEventListener('DOMContentLoaded', function(event) {
// array with texts to type in typewriter
var dataText = ["Cyber", "Sapa", "Synth", "CYBER // SAPA // SYNTH // TÔRTA // POMBADEV.2020"];
// 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 h2
document.querySelector("h2").innerHTML = text.substring(0, i + 1) + '<span aria-hidden="true"></span>';
// wait for a while and call this function again for next character
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);
}, 5000);
}
// 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);
});
如果有人可以幫助我,我將不勝感激!
PS。 Codepen 鏈接: https://codepen.io/iMorettini/pen/rNMOvZK
也許dataText[i].length
應該是您的line 33
的dataText.length
。 因為您正在檢查單詞,而不是單詞中的字母。
如果您可以發布項目的代碼筆或類似內容,將會很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.