2017-05-28 61 views
2
<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> 

它返回我說:setTimeout的變量外的範圍

undefinedundefinedundefinedundefinedundefinedundefinedundefined

所以問題是變量sc超出範圍因setTimeout功能,我已經已嘗試使用this

+0

它沒有超出範圍,它只是在超時發生時有錯誤的值。不,這與'this'無關。 – Bergi

回答

1

您問題的答案是使用Cl osures,你必須「保存」上下文。 你正在使用一個setTimeout函數,它在一段時間後執行你的函數,你的for循環可以說比20ms快,所以等到你的setTimeout執行你的函數時,計數器就已經是s.length,這就是爲什麼你得到undefined

// 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); 
+0

感謝您的幫助! :) – JustCodeIT