如何在数组javascript中使用split()和setTimeout()
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在数组javascript中使用split()和setTimeout(),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1540字,纯文字阅读大概需要3分钟。
内容图文
![如何在数组javascript中使用split()和setTimeout()](/upload/InfoBanner/zyjiaocheng/732/9367a76952304b3b9ea7c62e76ba2d2a.jpg)
这可能有点令人困惑: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中使用split()和setTimeout()全部内容,希望文章能够帮你解决如何在数组javascript中使用split()和setTimeout()所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。