The below function, Modify_Array_Argument(), takes a single argument that is an array. (See further down for an example of calling this function.) The function modifies the first three slots of the the passed array. Existing values (if any) in these slots are over-written.
function Modify_Array_Argument(a_array) { a_array[0] = "Fleetwood Mac"; a_array[1] = "Christine McVie"; a_array[2] = "Stevie Nicks"; }
The below function, Return_New_Array(), takes no arguments, but it returns a new array. It creates a new array each time called, fills the first three slots and returns the new array.
function Return_New_Array() { var my_array = new Array(); my_array[0] = "Jessy Greene Band"; my_array[1] = "Jessy Greene"; my_array[2] = "Joanna James"; return my_array; }
Below is a test function that does three test steps:
After each step, we print the array slots using a special "debug print" function. (See code sample at bottom.) Note that we pass the string for the first slot (0) to the Array constructor and manually populate the remaining two slots (1 & 2).
function Test_Arrays() { var ar = new Array("Little Feet"); ar[1] = "Paul Bararre"; ar[2] = "Richie Havens"; Write_Line(ar[0]); Write_Line(ar[1]); Write_Line(ar[2]); Modify_Array_Argument(ar); Write_Line(ar[0]); Write_Line(ar[1]); Write_Line(ar[2]); var ar2 = Return_New_Array(); Write_Line(ar2[0]); Write_Line(ar2[1]); Write_Line(ar2[2]); }
The output of the test function is below. The second test step demonstrates that an array passed into a function that modifies it actually is modified when that function returns. (In other words, the array was passed “by reference”.)
In the third step, a function that creates a new array successfully returns it to a calling function.
Little Feet Paul Bararre Richie Havens Fleetwood Mac Christine McVie Stevie Nicks Jessy Greene Band Jessy Greene Joanna James
Below is a function, Write_Line(), that takes one or more arguments and prints them to the current document stream. (This function is only useful on a webpage and only when the document is open for writing.) The function works best when you define a style for a <div class="JS"> block element. Each "line" you print through Write_Line() is a new <div> element.
function Write_Line(s) { document.write('<div class="JS">'); for (var ax=0; ax < arguments.length; ax++) { document.write(arguments[ax]); } document.writeln('</div>'); }
(back) | § | Top | Web | JavaScript | Tutorial |
---|