<script language="javascript">
// random strings
var strings = ["How is it even possible?", "Have you ever heard about this?"];
var WriteLine = function(s)
{
var end=s.length, sc=s.split("");
for(counter = 0;counter<end;counter++)
{
setTimeout(function(){document.write(sc[counter]);},20);
// ^^^^^^^^^^^
}
}
strings.forEach(WriteLine);
</script>
它告诉我:
undefinedundefinedundefinedundefinedundefinedundefinedundefined
问题是由于sc
函数,变量setTimeout
超出了范围,我已经尝试使用this
答案 0 :(得分:1)
您的问题的答案是使用Closures,您必须“保存”上下文。 您正在使用一个setTimeout,它会在一段时间后执行您的函数,并且您的for循环可以说比20 ms更快,所以当您的setTimeout执行时,您的函数计数器已经是s.length,这就是您未定义的原因
// random strings
var strings = ["How is it even possible?", "Have you ever heard about this?"];
var WriteLine = function(s)
{
var end=s.length,
sc=s.split("");
for(counter = 0;counter<end;counter++)
{
setTimeout((function(c){
document.write(sc[c]);
})(counter),20);
//
}
}
strings.forEach(WriteLine);