PDA

View Full Version : Passing Array to Function



locbtran
09-22-2011, 09:56 AM
I would like to pass an array to a function but how does the program know which array I would like to choose from??
Lets say I have 3 arrays and I would like to pass array C, to my function.
I checked the web but they only show if you have ONLY 1 array but NOT for multiple arrays.
How would I even go about doing this??



var arrA=new Array("fox.com","nbc.com","abc.com", "google.com");
var arrB=new Array("car","bike","boat", "plane");
var arrC=new Array("1","2","3", "4", "5", "6", "7", "8", "9");

function display(myArray){
myArray[1] = "changed";
}

display(myArray);

document.writeln(myArray[1]);

thanks

Minos
09-22-2011, 02:02 PM
Defined as they are, there is no need to pass anything, they are declared globally and can be referenced anywhere.

I'm not entirely sure what you are attempting to accomplish with your code...



var arrA=new Array("fox.com","nbc.com","abc.com", "google.com");
var arrB=new Array("car","bike","boat", "plane");
var arrC=new Array("1","2","3", "4", "5", "6", "7", "8", "9");


This is done correctly, creating three arrays, called arrA, arrB, arrC. This is how the program knows which array...they are all named something different. Did you mean something else?



function display(myArray){
myArray[1] = "changed";
}

display(myArray);


The first thing that actually gets executed here is the last line. The script calls the function display, and gives it contents of the variable 'myArray'...which contains nothing, because it hasn't been created. If you are attempting to send one of the arrays you created, it would read display(arrA), display(arrB), or display(arrC). Or even multiples display(arrA, arrB, arrC).

The function itself is written correctly, although it changes the SECOND item in the array and not the first. Array numbering starts at 0. Also, myArray would be a copy of the passed array, and that change would only affect the copy, not the original.



document.writeln(myArray[1]);

What's more, is that myArray would only exist INSIDE the function. So even though the function is fired before the above line, once it finishes and gets here, myArray no longer exists.

Realistically, since your arrays are global you don't have to pass anything.

display(){
arrA[0] ...
arrB[0] ...
arrC[0] ...
}

display();
would work fine. I just wanted to try and help you understand what was happening.