I am a total newbie in JavaScript, the syntax and the way objects and methods are linked together by a dot is a bit confusing to me at present. I am so much more comfortable using PHP procedural style. I have been using Robin Nixon's book "Learning JavaScript -- A Step by Step Guide". I have been taking codes off his book (as they have been presented) and have been running these scripts on my browser. But it seems that not all his codes are written properly. The following code writes out the names of animals, and this does work:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style></style>
</head>
<body>
<script>
displayItems("Dog", "Cat", "Pony", "Hamster", "Tortoise")
function displayItems(v1, v2, v3, v4, v5)
{
document.write(v1 + "<br>")
document.write(v2 + "<br>")
document.write(v3 + "<br>")
document.write(v4 + "<br>")
document.write(v5 + "<br>")
}
</script>
</body>
<html>
However, the author then attempts to use a FOR loop instead of repeating the same line five times, and I tried to implement this on my browser too, but I get a blank screen. I cannot figure out what might be wrong with this code. If the author of a 500 page book gets it wrong, then what hope is there?
<html>
<head>
<title></title>
<style></style>
</head>
<body>
<script>
displayItems("Dog", "Cat", "Pony", "Hamster", "Tortoise")
for(j = 0; j < displayItems.arguments.length; ++j)
document.write(displayItems[j] + "<br>")
</script>
</body>
<html>
3 Answers 3
Three things:
- You haven't declared the
displayItemsfunction you're calling - The
.argumentsproperty is deprecated, you should use theargumentsobject instead - You're not accessing the indices on the
argumentscollection but ondisplayItems
displayItems("Dog", "Cat", "Pony", "Hamster", "Tortoise")
function displayItems() {
for (var j = 0; j < arguments.length; ++j) {
// ^^^ don't forget to declare variables
document.write(arguments[j] + "<br>");
}
}
Comments
Just use it as an array:
displayItems = ["Dog", "Cat", "Pony", "Hamster", "Tortoise"]
for(var j = 0; j < displayItems.length; ++j)
document.write(displayItems[j] + "<br>")
1 Comment
Use this code, I have corrected it, always remember A function which is being called must be declared.
<html>
<head>
<title></title>
<style></style>
</head>
<body>
<script>
displayItems("Dog", "Cat", "Pony", "Hamster", "Tortoise");
function displayItems(v1, v2, v3, v4, v5)
{
for(j = 0; j < displayItems.arguments.length; ++j)
{
document.write(displayItems.arguments[j] + "<br>");
}
}
</script>
</body>
<html>