Forum Moderators: open

Message Too Old, No Replies

JavaScript undefined error

Getting the word undefined printed on screen after a loop

         

urbanmac

11:27 am on Aug 25, 2009 (gmt 0)

10+ Year Member




Hello

I have a simple Javascript that takes some words and at the ; between the words splits the content and makes them links. Problem is the word undefined is printed onscreen after the last link and I don't why?

Help appreciated.


<script type="text/javascript">
var meta = 'test1;test2;test3;test4;test5';
meta = meta.split(';');
// loop through our values
for (i=0;i<=meta.length;i++) {
document.write('<a href="http://www.google.com/search?&q='+meta[
i]+'">'+meta[i]+'</a> ');
}</script>

Fotiman

1:13 pm on Aug 25, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Your for loop is iterating one too many times. In your example, meta.length will equal 5. You are then looping from 0 to 5, so 0, 1, 2, 3, 4, 5 (that's 6 items, one more than you actually have). Change your for loop to this:

for (i = 0; i < meta.length; i++) {

urbanmac

1:27 pm on Aug 25, 2009 (gmt 0)

10+ Year Member



Thanks for the reply, I knew it was something easy!