Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialyoni ivan
957 PointsHow do i pass a Array parameter to a function ?
How do i pass a Array parameter to a function ?
function arrayCounter(myArray[]){
}
var myArray = new Array();
function arrayCounter(myArray){
}
both methuds dont work ! how do i do it right ?
4 Answers
Michael Austin
Courses Plus Student 7,814 PointsHi,
I’m not sure what you mean by it won’t be dynamic?
If you’re passing an array into a function, the array can be any length? You just have to manipulate the data in the function itself? For example (in this crude way):
var myArray = new Array('value1', 'value2');
var myArray2 = new Array('val3','val4','val5');
function arrayCounter(newArray){
for(i=0;i<newArray.length;i++){
alert(newArray[i]);
}
}
arrayCounter(myArray);
arrayCounter(myArray2);
Michael Austin
Courses Plus Student 7,814 PointsHi,
You need to remember to call the function itself.
Currently you’re creating the array:
var myArray = new Array(‘value1’, ‘value2’);
and creating the function
function arrayCounter(myArray){
alert(myArray[0]);
}
You just need to pass the array to the function now, by doing:
arrayCounter(myArray);
Don’t confuse where you define function arrayCounter(myArray) as it actually passing the variable myArray into it. The myArray you declare with var is a different scope to the one in the brackets of the function.
yoni ivan
957 PointsThis will work but it will not be dinamic, i will be able to pass in the function only to the amount of params that are in the array and i will be stricted.
yoni ivan
957 PointsIt works, thank you very much !
Dave McFarland
Treehouse TeacherDave McFarland
Treehouse TeacherHi yoni ivan Your JavaScript code needs to be formatted in a special way to appear correctly in the forum. I've fixed your code. For the next time, here are instructions: https://teamtreehouse.com/forum/posting-code-to-the-forum