如何在JavaScript数组中使用split()和setTimeout()函数

3

可能有点令人困惑 :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);
    }
}

抱歉nhahtdh,你能具体一些吗?:S - Ilir V. Gruda
2个回答

3
这是我的做法。不使用 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); });

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

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

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/


3
您遇到了典型的“循环闭包”问题。请查看JavaScript中循环内部的闭包 - 简单实用的示例。目前,当执行超时回调时,txt指向text[1]。尽管所有超时仍在执行,但您仍然比数组中的元素更频繁地调用txt.shift()
另一个问题是,任何延迟高达100ms几乎不会被人类注意到,因此您看不到任何增量。更糟糕的是,对于第一个短语,由于j0,所以所有超时都同时执行(几乎),因为delay * j + 100将导致100
最好逐个处理每个字母,而不是同时创建所有超时(请注意Blazemonger的解决方案是相同的,但更易理解,因为它更清晰)。
var text = [...];

function printLetter(phrase_index, letter_index) {
    var word = text[phrase_index];
    if (word) {
        if (letter_index === word.length) {
            printLetter(phrase_index + 1, 0);
        }
        else {
            var letter = word[letter_index];
            if (letter) {
                $('div#console_div').append('<br />' + letter);
                setTimeout(function() {
                    printLetter(phrase_index, letter_index + 1);
                }, 200);
            }
        }
    }
}

printLetter(0, 0);

DEMO


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接