2016-10-01 76 views
0

我正在使用webgl應用程序。我有starsList陣列,由於某種原因,當我運行這個功能:TypeError:x未定義 - JS

function initTextures() { 

     for (i = 0; i < starsList.length; i++) { 
      starsList[i].texture = gl.createTexture(); 
      starsList[i].texture.image = new Image(); 
      starsList[i].texture.image.onload = function() { 
       handleLoadedTexture(starsList[i].texture) 
      } 
      starsList[i].texture.image.src = starsList[i].name + ".gif"; 
     } 
    } 

我得到這個錯誤:

TypeError: starsList[i] is undefined 
handleLoadedTexture(starsList[i].texture) 

雖然在循環的第一行定義starsList[i].texture
有什麼想法爲什麼?

回答

0

當你的onload回調就是所謂的i等於starsList.length

所以starsList[starsList.length]是不確定的。

當您聲明您的回調 starsList[i].texture.image.onload = function() { handleLoadedTexture(starsList[i].texture) } 它不會複製一些具體的值starsList。當它被調用時,它會試圖找到範圍內的所有變量。

對於解決方案,您可以綁定每個onload回調以使用特定的i