how to pass an array as an argument to a function in javascript code example
Example 1: how to pass an array to a function
// Program to calculate the sum of array elements by passing to a function
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
// age array is passed to calculateSum()
result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += age[i];
}
return sum;
}
Example 2: js array as parameter
function myFunction(a, b, c) {//number of parameters should match number of items in your array
//simple use example
console.log("a: " + a);
console.log("b: " + b);
console.log("c: " + c);
}
var myArray = [1, -3, "Hello"];//define your array
myFunction.apply(this, myArray);//call function
Example 3: javascript function with array parameter
const args = ['test0','test1','test2'];
function call_me(param1, param2, param3){
//
}
call_me.apply(this, args);
Example 4: make a parameter array in js
var x = [ 'p0', 'p1', 'p2' ];
call_me(x);
function call_me(params) {
for (i=0; i<params.length; i++) {
alert(params[i])
}
}