在每个循环(JS)之间以任意时间循环遍历字符串数组

时间:2019-03-24 10:09:18

标签: javascript

我想创建一个动画,一次又一次地循环播放一个字符串。我的字符串中有两个数组:

let stringArray = ['TestOne', 'TestTwo'];

我想反复遍历所述数组(字符串一->字符串二->返回字符串一->字符串二-> ...连续)。我想一次打印一个字符串一个字符。在打印完所有字符后,我将清除打印的字符串并继续使用字符串2的字符。插图:

T
Te (250 ms after the first char)
Tes (250 ms after the second char)
Test (All characters are printed 250ms after the previous char)
TestO
TestOn
TestOne
T
Te
Tes
Test
TestT
TestTw
TestTwo
... (continue with TestOne again)

问题是,我希望每个字符在先前打印的字符之后仅250ms内打印。我该如何实现?

4 个答案:

答案 0 :(得分:2)

您可以使用一个this.state.quotes[this.state.rndNum].body is undefined 和一个显示间隔的数组。

数组indices开头包含两个值,indices表示[0, 0]的第一项,字符串中的第一个字符。

对于每个循环,字符索引都会增加,并根据字符串的长度检查该值。如果更大,则字符串的索引将递增,并将字符串索引重置为零。

为防止字符串索引大于实际的字符串计数,可通过进行余数分配来重置该值。

图案

stringArray

是IIFE(immediately-invoked function expression),它将数组作为第一个参数的值。它是数组的闭包,并允许将返回的函数用作该间隔的回调。

优点是拥有一个数据集,该数据集不能从外部更改,并且可以在任何回调调用中使用。

(indices => () => {
    // ...
})([0, 0])
let stringArray = ['TestOne', 'TestTwo'];

setInterval((indices => () => {
    document.getElementById('out').innerHTML = stringArray[indices[0]].slice(0, indices[1]);
    indices[1]++;
    if (indices[1] > stringArray[indices[0]].length) {
        indices[0]++;
        indices[1] = 0;
    }
    indices[0] %= stringArray.length;
})([0, 0]), 250)

答案 1 :(得分:1)

好吧,只要人们发布解决方案,我都会发布显而易见的,简单的解决方案,请参见评论:

{ // A scoping block so the variables aren't globals
  // (unnecessary if you're using modules)
    let stringArray = ['TestOne', 'TestTwo'];
    let arrayIndex = 0;
    let stringIndex = 1;
    // Start a timer that will call the callback every 250ms (or so)
    setInterval(() => {
        // Get the relevant string
        const str = stringArray[arrayIndex];
        // Output the substring
        console.log(str.substring(0, stringIndex));
        // Move to the next character
        ++stringIndex;
        // Need to move to next string?
        if (stringIndex > str.length) {
            // Yes, go back to the beginning of the string and
            // move to the next entry in the array, wrapping
            // around if we reach the end
            stringIndex = 1;
            arrayIndex = (arrayIndex + 1) % stringArray.length;
        }
    }, 250);
}

此部分:

arrayIndex = (arrayIndex + 1) % stringArray.length;

是一个方便的技巧,当您有一个索引(0 ... n-1)并想要增加它并循环时。假设您有3个条目,因此索引分别为0、1和2。当您位于2时,(2 + 1)3,而3 % 30,所以它是环绕。

答案 2 :(得分:0)

您可以执行此操作的一种方法是不使用循环,而是使用带有一些参数的函数,这样您就可以知道单词中的距离或长度,以及当前在阵列中打印的单词。

使用功能进行打印后,只需在功能中添加setTimeout(),即可控制延迟。有关JavaScript中超时的更多信息,请参见https://www.w3schools.com/jsref/met_win_settimeout.asp

答案 3 :(得分:0)

strings = [];
for (var i = 1; i <= "TestOne".length; i++)
  strings.push ("TestOne".substring (0, i));
for (var i = 1; i <= "TestTwo".length; i++)
  strings.push ("TestTwo".substring (0, i));
var position = 0;
setInterval (() => {
  console.log (strings [position++]);
  if (position == strings.length) position = 0;
}, 250);