【问题标题】:Cannot read property 'length' of undefined - Error in JavaScript无法读取未定义的属性“长度” - JavaScript 中的错误
【发布时间】:2021-03-15 20:31:10
【问题描述】:

我正在使用重现打字机效果的代码学习 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

【问题讨论】:

  • 在setTimeout setTimeout(function({ StartTextAnimation(0); }, 5000); return之后添加return语句,否则会跳转到下一个出错的if语句

标签: javascript html css arrays function


【解决方案1】:

也许dataText[i].length 应该是您的line 33dataText.length。因为您正在检查 words ,而不是 words 中的字母。

如果您可以发布项目的代码笔或类似内容,将会很有帮助。

【讨论】:

  • 嗨 Anurag,这是 codepen 链接:codepen.io/iMorettini/pen/rNMOvZK 谢谢!
  • 事实上,这个解决方案奏效了!感谢您的帮助,我是初学者,有时我最终会错过细节......
  • @mitya 我没有足够的声誉来发表评论。
  • @AmandaMorettini 我也是初学者。我最近也犯了这样的错误,所以我注意到了你的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2020-06-02
  • 2015-02-05
  • 2020-04-19
  • 2017-11-25
  • 2021-10-21
  • 2021-02-26
相关资源
最近更新 更多