Reputation: 5
I'm currently working through Robin Nixon's Learning PHP, MySQL, Javascript, CSS & HTML5, 4th Edition, and I'm at a part where he explains how to return an array of variables from a function.
The code he used to demonstrate this is:
words = fixNames("the", "DALLAS", "CowBoys")
for(j = 0 ; j < words.length ; ++j)
document.write(words[j] + "<br>")
function fixNames()
{
var s = new Array()
for (j = 0 ; j < fixNames.arguments.length ; ++j)
s[j] = fixNames.arguments[j].charAt(0).toUpperCase() +
fixNames.arguments[j].substr(1).toLowerCase()
return s
}
When I was writing this code, I wrote it:
words = fixNames2("the", "DALLAS", "CowBoys")
for(j = 0; j < words.length; ++j) {
document.write(words[j] + '<br>')
}
function fixNames2() {
var s = new Array()
for(j = 0; j < fixNames2.arguments.length; ++j) {
s[j] = fixNames2.arguments[j].charAt(0).toUpperCase() +
fixNames2.arguments[j].substr(1).toLowerCase()
return s
}
}
I know in an earlier part of the book, he mentions that you don't need to surround single statements with curly braces, and I thought the second for
conditional was 2 statements (the s[j]
part, and the return s
part), so I surrounded the whole thing with curly braces, but for some reason, when written this way, the code only outputs the first word in the array ('the', but correctly formatted by the function so that it's 'The').
I was wondering if anyone could explain to me why this is? Is it that the 2nd for
conditional is actually only actually 1 statement? Or does it perhaps have something to do with the way I nested the curly braces?
Upvotes: 0
Views: 203
Reputation: 51898
The "return" is not part of the for loop (it's a part of the function) but you included it within those braces -- so it's not going to work the way the original author intended.
So:
for(j = 0; j < fixNames2.arguments.length; ++j) {
s[j] = fixNames2.arguments[j].charAt(0).toUpperCase() +
fixNames2.arguments[j].substr(1).toLowerCase()
return s //// WRONG
}
Should be:
for(j = 0; j < fixNames2.arguments.length; ++j) {
s[j] = fixNames2.arguments[j].charAt(0).toUpperCase() +
fixNames2.arguments[j].substr(1).toLowerCase()
}
return s;
Or you can even do away with the brackets, since it's just one statement in the for loop:
for(j = 0; j < fixNames2.arguments.length; ++j)
s[j] = fixNames2.arguments[j].charAt(0).toUpperCase() +
fixNames2.arguments[j].substr(1).toLowerCase();
return s;
Note that even though it's on two lines it's considered to be one statement as it should end with a semicolon.
Also,
s =
x
+
y
+
z;
is considered one statement of code. The way to know if something is considered to be a statement is that it's generally ended with a semicolon.
ALWAYS use semicolons to end a statement. It's bad practice not to (even if it runs).
Upvotes: 1