我试图循环遍历一个指定的字符串,该字符串已被分割成单个字符,然后以自动收报机磁带的方式读回它们。我在 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>
最佳答案
遵循 @UnholySheep 和 @user3713422 的评论,包括在 myFunction
范围之外声明 myvar
,删除对未定义 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>
关于javascript - 通过引用 javascript 中的函数来循环遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40964277/