javascript - 未捕获的类型错误:无法读取未定义数组的属性“长度”
问题描述
我想创建一个函数来为打字机等文本设置动画。我不明白为什么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
函数的闭包有疑问。
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 - Google Sheets Script – 输出单元格背景颜色的函数
- javascript - 如何在 JS 中获取数组而不是对象的数据?
- java - java.lang.NoSuchMethodError: org.json4s.jackson.JsonMethods$.parse$default$3()Z
- git - 如何比较 CloudBuild 中的 Git 分支?
- python - 调用函数从另一个 python 文件获取 JSON 响应结果
- sql - SQL单查询
- python - 错误:命令错误退出状态1。安装geopandas时
- mysql - 显示重复数据mysql和where子句
- arrays - 同类型约束 'Element' == 'Array
' 是递归的 - android - 在 Android 中将图像压缩到 200KB 字节大小