javascript - 如何在数组 javascript 中使用 split() 和 setTimeout()

标签 javascript jquery split settimeout

可能有点困惑:S

如果有人能帮我把一个字符串数组拆分成字母。而不是用暂停录音。就像在 DOS 中一样。

我可以用单个字符串做到这一点,但我不能在数组中做到这一点。

这是我的代码:

var text = new Array();
text[0] = "welcome ".split('');
text[1] = "how are u?".split('');
var delay = 20;
for (var j = 0; j < text.length; j++) {

    var txt = text[j];
    for (u = 0; u < txt.length; u++) {
        setTimeout(function () {
            $('div#console_div').append('<br />' + txt.shift());
        }, delay * j + 100);
    }
}

最佳答案

这就是我要做的。使用递归函数代替 for 循环,该函数根据它在字符串中的位置使用不同的参数调用自身:

var text = new Array();
text[0] = "welcome ".split('');
text[1] = "how are you?".split('');
var delay = 400;

function addOneChar(i, j) {
    $('#console_div').append('<br>' + text[i][j]);
    if (j+1<text[i].length) {  // next character in the current string
        setTimeout(function() { addOneChar(i, j+1); }, delay);
    } else if (i+1<text.length) {   // start the next string in the text[] array
        setTimeout(function() { addOneChar(i+1, 0); }, delay);
    } // else quit
}

setTimeout(function() { addOneChar(0,0); });

http://jsfiddle.net/mblase75/tkEDN/

我们可以通过将 text[] 组合成一个字符串并使用 .charAt() 来提取字符来进一步简化:

var text = new Array();
text[0] = "welcome ";
text[1] = "how are you?";
var delay = 400;
var textstr = text.join('');

function addOneChar(i) {
    $('#console_div').append('<br>' + textstr.charAt(i));
    if (i+1<textstr.length) {
        setTimeout(function() { addOneChar(i+1); }, delay);
    } // else quit
}

setTimeout(function() { addOneChar(0); });

http://jsfiddle.net/mblase75/MYtjy/

关于javascript - 如何在数组 javascript 中使用 split() 和 setTimeout(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14774966/

相关文章:

javascript - 无法在主干 View 中定义两个事件

javascript - 隐藏div中的jqGrid宽度不正确

javascript - jQuery,使元素以不同的速度滚动

javascript - 在 Jquery 中使用 .css() 中的变量

string - 带有元字符的 R 中的 strsplit

javascript - 用 .split() 结果覆盖源变量

javascript - svelte 组件中的动画

javascript - 使用 jQueryeach() 动态添加图像到 div ..不知何故,它们都添加到最后一个 div

php - 我需要根据访客视口(viewport)调整图片大小

java - 从 URL 解析字符串值