可能有点困惑: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); });
关于javascript - 如何在数组 javascript 中使用 split() 和 setTimeout(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14774966/