2013-02-08 54 views
3

它可能有点令人困惑:S如何在数组中使用split()和setTimeout()javascript

如果任何人都可以帮助我将字符串数组拆分为字母。而不是用超时的磁带。像在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); 
    } 
} 
+0

对不起nhahtdh但你可以更具体:S – 2013-02-08 14:51:33

回答

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); }); 

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/

+0

+1比我的解决方案:) – 2013-02-08 14:58:00

+1

@FelixKling的好评更优雅,谢谢。 :-) – Blazemonger 2013-02-08 14:59:18

3

您有典型的“闭环闭环”问题。看看JavaScript closure inside loops – simple practical example。在执行超时回调时,txt指的是text[1]。所有的超时仍然会被执行,所以你比数组中的元素更经常地调用txt.shift()

另一个问题是任何延迟到100ms都不会被任何人看到,所以你看不到任何增量。更糟糕的是,对于第一个短语,所有超时都在同一时间(几乎)执行,因为j0delay * j + 100将导致100


你是最好的处理每一个字母一个接一个,而不是一次创建所有超时(注意:Blazemonger's solution是一样的,但更容易理解,因为它是清洁剂)。

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