Javascript:检查字符串是否包含字符,然后删除字符串的一部分?

标签 javascript string character contains intervals

本质上,该函数的作用是从输入文本中获取单词列表,并按照客户从下拉菜单中选择的间隔 (WPM) 将其设置在显示屏上。

如果函数中传递的单词包含问号、句号、冒号、分号、感叹号或逗号,则将其删除,并且所选间隔加倍。例如,如果字之间的延迟为 117 毫秒,则为 234 毫秒。

我在确定传递的单词是否包含标点符号并将其删除的部分中遇到了最大的麻烦。

我收到一个错误: 未捕获类型错误:无法读取未定义的属性“indexOf”。

我不知道为什么会发生这种情况,因为 list[index++]StringindexOf是 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/

相关文章:

c++ - 为什么从流中提取字符串会设置 eof 位?

python - 行继续字符 python 后的语法错误意外字符

javascript - 错误: Protocol JSON API error running Lighthouse with TestCafe Server

javascript - 提取 iframe 内的脚本

javascript - 限制使用特定字符的正则表达式(如拼字游戏字母组)

ruby - 如何在 Ruby 中随机取一段字符串?

javascript - 如何添加类型以在 Node v12 中使用 Intl.ListFormat

C - 从文本文件中读取字符串并按大小排列

android - 读取 Android 中的任何文本文件并将内容转换为 UTF-8?

r - 如何从字符对象创建字符向量?