2016-02-04 67 views
0

我一直在爲類進行一些編碼,並且在編碼交通燈系統時遇到了問題。這裏是我的代碼,錯誤顯然是21和22左右,是一個'Uncaught Typeerror'。你能告訴我一些提示嗎?Uncaught Typeerror,無法讀取未定義的屬性'1'

<html> 
<body> 
    <script> 
     var trafficlights [ "red.png", "orange.png", "green.png"]; 
     var index = 0; 

     function traffic() { // this part is tricky 
      index = index + 1; 
      if (index == index.length) 
       index = 0; 

      var image = document.getElementById('light')[0]; 
      image.src = trafficlights[index].value = data; 
     } 
    </script> 

    <img id="light" src="red.png" style="width:250px;height:250px;"> 
    <button type="button" onclick= "traffic()">click to change lights</button> 
</body> 
</html> 
+2

這是一個錯字;你在這行忽略了一個'=':'var trafficlights = [「red.png」,「orange.png」,「green.png」];'另外,研究[Modulo operator](https:// developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_())來保存您的'trafficlights.length'檢查。 –

+0

你爲什麼要做'index == index.length'?訪問一個整數的不存在的'length'屬性將總是返回undefined' – LostMyGlasses

+0

ok多虧了幫助 –

回答

0

這裏有幾個語法錯誤:

var trafficlights [ "red.png", "orange.png", "green.png"]; 

應該

var trafficlights = ["red.png", "orange.png", "green.png"]; 
       ^^^ 

在這裏:

if (index == index.length) 

沒有定義到一個length數量,也是它就沒有真正意義的數字與爲它的「長度」,但我覺得你的意思是這樣:這裏還

if (index == trafficlights.length) 
      ^^^^^^^^^^^^^ 

var image = document.getElementById('light')[0]; 

document.getElementById返回單個元素;不是一個數組。因此,它應該是這樣的:

var image = document.getElementById('light'); 

並且最後在這裏:

image.src = trafficlights[index].value = data; 

什麼是data?我不認爲你需要它,當你提到一個數組值時,你可以這樣稱呼它:

image.src = trafficlights[index]; 
+0

非常感謝你!它的工作現在和你所有的天才 –

+0

@samfinlay很高興我能幫忙! –

相關問題