【发布时间】:2017-04-19 06:10:21
【问题描述】:
我正在尝试遍历已拆分为单个字符的指定字符串,然后将它们读回自动收报机样式。我在 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>
【问题讨论】:
-
如果
c是一个对象,那么res[c]应该访问什么?你的意思是写res[c.value]? -
您将
counter与res.length进行比较,而不是counter.value。 -
啊,感谢这些 cmets,我已经相应地调整了代码并且效果更好,即使我现在的输出超过了字符数组的末尾,天哪!
-
这个问题(很可能)是由于检查
if( counter.value > res.length ) clearInterval(myVar);只执行一次,当页面加载并执行myFunction()时。相反,您可能希望在每次执行appendText后执行此检查 -
myvar和myVar也是不同的变量名。
标签: javascript pass-by-reference setinterval pass-by-value