本质上,该函数的作用是从输入文本中获取单词列表,并按照客户从下拉菜单中选择的间隔 (WPM) 将其设置在显示屏上。
如果函数中传递的单词包含问号、句号、冒号、分号、感叹号或逗号,则将其删除,并且所选间隔加倍。例如,如果字之间的延迟为 117 毫秒,则为 234 毫秒。
我在确定传递的单词是否包含标点符号并将其删除的部分中遇到了最大的麻烦。
我收到一个错误: 未捕获类型错误:无法读取未定义的属性“indexOf”。
我不知道为什么会发生这种情况,因为 list[index++]
是 String
和indexOf
是 Javascript 中字符串的一种方法,而不是属性。
我也不确定如何实现延迟。鉴于我已经使用过 setInterval()
这样(我只能使用 setInterval 来达到此目的)我不确定如何让它设置 String
显示两次,同时还包括延迟。
function runDisplay(data, id) {
var reader = document.getElementById(id);
var index = 0;
if (timer) {
clearInterval(timer);
}
if (data.length) {
timer = setInterval(function() {
var punctuation = [".", ",", ":", ";", "!", "?"];
var textSpeed = 117; // default
for (var j = 0; j < punctuation.length; j++) {
// remove punctuation if found and double text delay
// if multiple found, remove only one
if (!(data[index++].indexOf(punctuation[j]) === -1)) {
data[index++] = string.replace(punctuation[j], '');
// set data[index++] to display twice to double delay?
}
}
reader.innerHTML = data[index++];
index = index % data.length;
}, textSpeed);
}
}
最佳答案
I'm getting an error: Uncaught Type Error: Cannot read property 'indexOf' of undefined.
I'm not sure why this is happening since list[index++] is a String and indexOf is a method of Strings in Javascript and not a property.
首先,方法也是对象的属性。
其次,JS 引擎告诉您正在对 undefined
调用 indexOf
,因此它不是字符串。并且 data[index++]
未定义,因为 index
可能不是 data
数组范围内的索引。
该函数的主要问题是,如果 data
是一个字数组,则无法正确迭代它。在这里,每次读取数组时都会递增 index
,每次显示时 index
只应递增一次。
I'm also not sure how I would implement the delay. Given that I've used setInterval() in this way (and I can only use setInterval for the purposes of this) I'm not sure how I would get it to set the String in the display twice while also including the delay.
如果函数必须在无限循环中显示所有单词(这就是 index = index % data.length
的目的,对吗?),可以在匿名内部调用clearInterval 和另一个setInterval函数传递给当前的 setInterval,允许计算您想要的 textSpeed。
关于Javascript:检查字符串是否包含字符,然后删除字符串的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100600/