首页 > 解决方案 > 未捕获的类型错误:无法读取未定义数组的属性“长度”

问题描述

我想创建一个函数来为打字机等文本设置动画。我不明白为什么words[index].length在 setInterval 函数中返回 undefined 。

let speed = Math.floor(Math.random() * 1000); 

function typeWriter() {
    let words = ["Achieve", "Attain"]; /* The text */ // 6

    let typeWriter = document.getElementById("typewriter");
    let i = 1;
    let index = 0;
    while (index < words.length) {

        setInterval(() => {

            if (i <= words[index].length && i > 0) {
                typeWriter.innerHTML = words[index].slice(0, i);

                if (i == words[index].length) {
                    i = -1;
                }else {
                    i++;
                }
            } else if ((i * -1) <= words[index].length && i < 0) {
                typeWriter.innerHTML = words[index].slice(0, i);

                if ((i * -1) == words[index].length) {
                    clearInterval();
                }else {
                    i--;
                }
            }

            speed = Math.floor(Math.random() * 1000);

       }, speed);

       if (index == words.length) {
           index = 0;
       } else {
           index++
       }
    }
}

标签: javascriptarrays

解决方案


您对setInterval函数的闭包有疑问。

while (index < words.length) {
    const word = words[index]; // fetch word from the array as a constant
    setInterval(() => {

        if (i <= word.length && i > 0) {
            typeWriter.innerHTML = word.slice(0, i); // use word reference

    ...

您需要在调用之前将值获取到常量setInterval,然后使用它。因为所有代码都在单个代码块内,所以在执行 setInterval 块之前修改您的索引变量。所以你需要让你的setInnterval代码执行独立于索引变量。

第二种解决方案是将您的 setInterval 移动到第二个函数,该函数接收索引作为参数。这样,索引值将被复制并且不会在此块内更改,即使原始值会更改。


推荐阅读