未捕获的Typeerror,无法读取未定义的属性“1”

时间:2022-09-05 19:42:32

I have been doing some coding for class and I ran into a problem whilst coding for a traffic light system. Here is my code, the error is apparently around 21 and 22 and is an 'Uncaught Typeerror'. Could you please show me a few tips?

我一直在为课程做一些编码,在编写交通灯系统时遇到了问题。这是我的代码,错误显然是在21和22左右,是一个'Uncaught Typeerror'。你能告诉我一些提示吗?

<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>

1 个解决方案

#1


0  

There are a few syntax errors here:

这里有一些语法错误:

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

Should be

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

And here:

if (index == index.length)

There isn't a length defined onto a number, and also it wouldn't really make sense to compare a number to its "length", but I think you meant to do this:

数字上没有定义长度,将数字与“长度”进行比较也没有意义,但我认为你的意思是这样做:

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

Also here:

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

document.getElementById returns a single element; not an array. So it should look like:

document.getElementById返回单个元素;不是一个数组。所以看起来应该是这样的:

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

And lastly here:

最后这里:

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

What is data? I don't think you need it, and when you refer to an array value you just call the element like so:

什么是数据?我认为你不需要它,当你引用数组值时,你只需要调用元素:

image.src = trafficlights[index];

#1


0  

There are a few syntax errors here:

这里有一些语法错误:

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

Should be

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

And here:

if (index == index.length)

There isn't a length defined onto a number, and also it wouldn't really make sense to compare a number to its "length", but I think you meant to do this:

数字上没有定义长度,将数字与“长度”进行比较也没有意义,但我认为你的意思是这样做:

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

Also here:

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

document.getElementById returns a single element; not an array. So it should look like:

document.getElementById返回单个元素;不是一个数组。所以看起来应该是这样的:

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

And lastly here:

最后这里:

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

What is data? I don't think you need it, and when you refer to an array value you just call the element like so:

什么是数据?我认为你不需要它,当你引用数组值时,你只需要调用元素:

image.src = trafficlights[index];