0

Maybe I've just been staring at this screen for too long, but I cannot seem to work out why this for loop is hanging?

var not = '3,7';
var nots = not.split(',');
alert(nots.length);
for (var i = 0; i <= nots.length; i++) { 
    nots[i] = parseInt(nots[i], 10);
}
document.write(nots);

Thanks for any help.

Cheers
Charlie

1
  • 2
    Have you considered using Firefox with Firebug. Excellent toolset for debugging Javascript. Commented Aug 28, 2011 at 6:55

1 Answer 1

5

In the loop you are testing if i <= nots.length. You should be testing if i < nots.length.

When the length is 5, there will elements at indexes 0, 1, 2, 3, 4. So when i reaches 5, there are no more elements. But then you set nots[i] (element 5) and extend the array by one. So each time the loop executes when i is equal to nots.length, you are extending the array by one, and so the loop runs "just one more time" only to extend the array further.

Sign up to request clarification or add additional context in comments.

2 Comments

Of course!, because I came from a for-in, i didn't think to be counting only to <. Thankyou :)
One frequently-used pattern to avoid this is for (var i = 0, l = nots.length; i < l; i++)

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.