Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Chris

Chris Avatar

******
Head Coder

19,519


June 2005
I expect you to know the following things before reading this tutorial.

- Arrays and ".length"
- if()
- for()
- functions

That should be all you NEED to know, but an extensive knowledge can always help.

Now that that is out of the way, I'm gonna explain to you this code.
<script>
function writeThis (){
if(arguments.length > 0){
for(a=0;a<arguments.length;a++){
document.write(arguments[a]);
}
}
}


writeThis("Dude ","I Hate"," You :D");
</script>


And then I'll explain why its better then this one.


<script>
function writeThis (ext1,ext2,ext3){
document.write(ext1+ext2+ext3);
}


writeThis("Dude ","I Hate"," You :D");
</script>


Now first off, we have the standard opening line. Go ahead and ignore that and the ending line for now.

The next line is the line creating the function, called writeThis. Now, if you look where there is normally the list of parameters (arguments), there are none. You may be thinking, "What? Why are there no parameters if they call parameters later?"

First off, the answer to that is this. There are no parameters defined, because I'm teaching you a different way.

Now, we go to the next line. Its an if() statement, containing "arguments.length > 0" Well, here's where the knowledge of arrays come in. You should know,t hat ".length" is used to say how many different levels there are in an array. Now, that means "arguments" is an array.... but for what?

Its an array containing all parameters set to the function. So, basically, it contains all parameters listed. Now, onto its point. It currently is saying that there are parameters, cause its greater then 0.

Now, onto the next line. Its just a for() loop, and it goes through the loop of the arguments.

The next line just writes what the parameter actually is, and then after that we have the 3 ending brackets. Last two lines contain the calling function, and then the final calls the script end tag.

Now, we'll compare it to the other code. The other code, is extremely simple, and shorter. But less effecient. Say you wanted to add more parameters to the code. Well, the first one would work fine, but the second one would mess up and you'd have some problems.


Aaron

Aaron Avatar
Bad Wolf

****
Dedicated Studio Member

859


November 2006
Ah, thank you very much. :)

newBookmarkLockedFalling