我试图遍历指定的字符串,该字符串已拆分为单个字符,然后将其读回自动收录器磁带样式。我在setInterval中有一个函数,它应该增加一个字计数器,但我很难让它工作,因为我无法通过引用将计数器(整数)发送到函数中。我已经阅读过本网站上的各个页面以及其他有关按价值传递和参考传递的页面,我仍然无法让它发挥作用。有人可以帮忙吗?我最近的化身在下面 - 它不起作用:(
<!DOCTYPE html>
<html>
<body>
<span id="demo"></span>
<script>
myFunction();
function myFunction()
{
var str = "How are you/doing today?";
var res = str.split(""); // we now have an array of individual letters
// The "/" is intended to be a line break
var counter = { value: 0 }; // keeps track of where we are
myvar = setInterval( appendText, 250, res, counter ); // Run every 250ms
if( counter.value > res.length ) clearInterval(myVar); // when we read the end of the character array, stop the read out.
}
function appendText( res, c )
{
var addtext;
if ( res[c.value] =="/" )
{
addtext="<br/>";
}
else
{
addtext = res[c.value];
}
document.getElementById("demo").innerHTML+=addtext;
c.value++; // c is a counter that keeps track of where we are in the text string
}
</script>
</body>
</html>
答案 0 :(得分:1)
根据@UnholySheep和@ user3713422的评论,并在myvar
范围之外声明myFunction
,删除对未定义myVar
的引用
<!DOCTYPE html>
<html>
<body>
<span id="demo"></span>
<script>
myFunction();
var myvar;
function myFunction() {
var str = "How are you/doing today?";
var res = str.split(""); // we now have an array of individual letters
// The "/" is intended to be a line break
var counter = {
value: 0
}; // keeps track of where we are
myvar = setInterval(appendText, 250, res, counter); // Run every 250ms
}
function appendText(res, c) {
var addtext;
if (res[c.value] == "/") {
addtext = "<br/>";
} else {
addtext = res[c.value];
}
document.getElementById("demo").innerHTML += addtext;
c.value++; // c is a counter that keeps track of where we are in the text string
// when we read the end of the character array, stop the read out.
console.log(c.value, res.length);
if (c.value === res.length) clearInterval(myvar);
}
</script>
</body>
</html>
&#13;
答案 1 :(得分:0)
你可以直接使用字符串,因为它也具有长度属性。并且可以使用索引轻松访问角色。
function myFunction() {
var res = "How are you/doing today?",
counter = { value: 0 };
myInterval = setInterval(appendText, 250, res, counter);
}
function appendText(res, c) {
document.getElementById("demo").innerHTML += res[c.value] == "/" ? "<br/>" : res[c.value];
c.value++;
if (c.value === res.length) clearInterval(myInterval);
}
var myVar;
myFunction();
&#13;
<span id="demo"></span>
&#13;