简体   繁体   English

javascript for循环行为异常

[英]javascript for loop not behaving as expected

I know this is really basic but I am new to Javascript 我知道这真的很基础,但是我是Java语言的新手

This is a piece of code from a battleship game I am working on for a class 这是我正在上一堂课的战舰游戏的一段代码

function displayMyBoats(ship){

    for (var i = 0; i<ship.length; i++) 
    {
        alert("ship.length = " + ship.length);
        alert("Ship[i]= " + ship[i]);
        document.getElementById( "Set_" + ship[i] ).src = fnImageShip;
        alert("i = " + i);
    }
}

I am testing with a ship array that is 5 elements. 我正在测试包含5个元素的舰船阵列。 Everything works fine until it reaches 5, then all of a sudden it thinks the length of the array is 8. 一切正常,直到达到5,然后突然认为数组的长度为8。

There is no code to increase the length of ship array, so what would cause it to add to the length of the array? 没有代码可以增加船长的长度,那么会导致它增加船长的原因是什么呢?

The alerts are my testing to see what all the values are at. 警报是我的测试,以查看所有值是多少。

To give you a hint, try adding an alert whenever your script is either entering or exiting the displayMyBoats() . 为了给您一个提示,请在脚本进入或退出displayMyBoats()时尝试添加警报。 Suddenly jumping to 8 indicates that it's entering the method a second time, this time with a ship of len 8. 突然跳到8表示它是第二次进入方法,这一次是len 8。

Confirm or deny this theory by adding this alert after your for loop block: 通过 for循环块之后添加以下警报来确认或否认这一理论:

 alert('exiting displayMyBoats()');`

Perhaps you see more if you use console.log(ship); 如果使用console.log(ship),也许您会看到更多; instead of alert(); 而不是alert(); - if you are using Firebug/Console. -如果您使用的是Firebug /控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM