javascript - 为什么我得到 'TypeError: Cannot read property ' length' of undefined'

标签 javascript typeerror

我正在尝试使用 vanilla JS 创建打字效果,但出于某种原因,我不断收到 TypeError: Cannot read property 'length' of undefined 错误。我不明白为什么,因为定义了“单词”。它困扰了我一段时间,我是那种喜欢尝试自己找到正确答案的人,但我完全被困住了。

var sentence = document.getElementsByClassName('sentence')[0];
var words = ['websites', 'apps', 'games'];
var speed = 100;
var i = 0;
var j = 0;

function type(word) {
	if(i<word.length) {
  	sentence.innerHTML += word.charAt(i);
    i++;
    setTimeout(function() { type(word); }, speed);
  }
}

function backspace(word) {
    if(j<word.length) {
        sentence.innerHTML = sentence.innerHTML.slice(0, -1);
        j++;
        setTimeout(function() { backspace(word); }, speed);
  }
}

function check() {
    if(j < words.length) {
        setTimeout(function() { type(words[j]); }, 1000);
        j++;
        check();
    }
}

check();
* {
    font-family: Arial;
  }
  
  .container {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .cursor {
    background: #000;
    width: 2px;
    height: 15px;
    animation: blink 1s steps(5, start) infinite;
  }
  
  @keyframes blink {
    to { visibility: hidden; }
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles.css">
    <title>Typing Effect Example</title>
</head>
<body>
    <div class="container">
        <div class="sentence">We make </div>
        <div class="cursor"></div>
    </div>

    <script src="scripts.js"></script>
</body>
</html>

最佳答案

您传递给 setTimeout 的函数在给定的持续时间到期之前不会被评估,正如您所期望的那样。那时,您的 j 将是 3,并且 words[3] 未定义。因此,(undefined).length 给你一个错误。

打开浏览器开发工具并通过堆栈溢出运行代码段,然后在发生错误的地方设置断点。当你被卡住时,这应该是你的第一 react 。

关于javascript - 为什么我得到 'TypeError: Cannot read property ' length' of undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292479/

相关文章:

javascript:如何阻止页面重新加载?

javascript - 如何检查属性是否为具有属性 "__deferred"的对象

javascript - AngularJS 嵌套 Controller

Python 类型错误 : not enough arguments for format string

javascript:由于通配符,获取被 CORS 策略阻止

javascript - Chart.js 将数据点减少一半

javascript - JS 异常仍然能够潜入,但很少,不知道为什么

python - TypeError:无法根据规则 ('O' 将数组数据从 dtype ('float64' ) 转换为 dtype 'safe' )

Python 运算符重载

Haskell 类型错误消息