我一直在爲類進行一些編碼,並且在編碼交通燈系統時遇到了問題。這裏是我的代碼,錯誤顯然是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>
這是一個錯字;你在這行忽略了一個'=':'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'檢查。 –
你爲什麼要做'index == index.length'?訪問一個整數的不存在的'length'屬性將總是返回undefined' – LostMyGlasses
ok多虧了幫助 –