weird results with for-in loop
Hi all,
I'm doing one of the exercises in the Beginning Javascript book and I'm getting weird results with a for-in loop. I have a page with 5 links to different sites. What I want to do when the page loads is use a for-in loop to cycle through the links[] array and pop up each link name as an alert. However, I end up getting 3 extra alerts that say "undefined", "item", and "namedItem". I'm confused because links.length gives me 5, but the loop gives me 8 alerts. My code is below. Can someone help? Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JavaScript Testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body language=JavaScript onload="displaylinks()">
<script language="javascript" type="text/javascript">
function displaylinks()
{
var links = document.links;
var index;
alert (links.length);
for (index in links)
{
alert (links[index].name);
}
}
</script>
<a href="http://www.yahoo.com" name="yahoo">Yahoo</a>
<br>
<a href="http://www.espn.com" name="espn">ESPN</a>
<br>
<a href="http://fantasysports.yahoo.com" name="fantasy">Fantasy Sports</a>
<br>
<a href="http://www.hotmail.com" name="hotmail">Hotmail</a>
<br>
<a href="www.google.com" name="google"> Google </a>
</body>
</html>
|