繁体   English   中英

未捕获的类型错误:无法读取未定义数组的属性“长度”

[英]Uncaught TypeError: Cannot read property 'length' of undefined array

我想创建一个 function 来为打字机等文本设置动画。 我不明白为什么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++
       }
    }
}

您对setInterval function 的闭包有疑问。

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 移动到第二个 function,它接收索引作为参数。 这样,索引值将被复制并且不会在此块内更改,即使原始值会更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM