-1

I know this is really basic but I am new to Javascript

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. Everything works fine until it reaches 5, then all of a sudden it thinks the length of the array is 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.

3
  • It should be some other part of the code which causes this. I mean, there could be event handlers which trigger onpropertychange of Set_" + ship[i] for example. Commented Mar 4, 2011 at 23:04
  • It's hard to say anything from this -- can you show where you create the array and pass it to the function? Commented Mar 4, 2011 at 23:06
  • 1
    See this: jsfiddle.net/wb4TW sfrocks is correct. This code works fine. Something else must be causing an error. Commented Mar 4, 2011 at 23:08

2 Answers 2

2

To give you a hint, try adding an alert whenever your script is either entering or exiting the displayMyBoats(). Suddenly jumping to 8 indicates that it's entering the method a second time, this time with a ship of len 8.

Confirm or deny this theory by adding this alert after your for loop block:

 alert('exiting displayMyBoats()');`
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps you see more if you use console.log(ship); instead of alert(); - if you are using Firebug/Console.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.