How to pass an array as a parameter to function?

Asked

Viewed 9,032 times

4

How do I pass an array as a parameter to a function? This way I did not work.

var arr = [7,4,2,12,10,9,17,20];

function soma(num1,num2) {
    resul = num1 + num2;
    return resul;
}
document.write(soma(arr[]));
  • Tell us what your goal is. You’re adding up the two arguments, but passing an array. It’s not clear to me.

  • Document.write(sum(arr[0],arr[1]); it is a possibility ...

  • It’s just that I’m starting with javascript and had doubts about how to do this, but I found that I have to pass the positions of the array to be able to work, Thanks to all.

  • Ah one more thing in the variable "resul" below it is better to put the "var" before so "var resul = num1 + num2;", because it worked without putting the "var" Function soma(num1,num2) { resul = num1 + num2; Return resul; }

  • But be careful about the size of the array. See that you have an array with 8 values and want to pass as parameter to a two argument function.

  • 1

    Yeah, you better put the var before, always. See https://answall.com/a/2517 and https://answall.com/a/927

  • Antonio, I was alone with my cell phone when I answered first, but now I improved the answer and explained. That’s what you were looking for?

Show 2 more comments

1 answer

8

To pass an array and "distribute" its elements by the arguments of a function you can do in different ways.

You can do "by hand" as you have in the question and it should be avoided because it is not flexible. Or you can use .apply() or the modern way ES6.

Using .appy() you can pass the array as the second argument of the method:

var res = soma.apply(null, arr):

Using ES6 ("spread Arguments syntax") is even simpler and uses only ... before the array:

var res = soma(...arr):

Both methods do what you want. Then inside the function, if you don’t have a fixed number of arguments you can use the reserved word arguments that within the function gives you access to all arguments. It is not an array, but almost, you can convert to array with [...arguments].

Example:

function somar() {
  return [...arguments].reduce((sum, nr) => sum + nr, 0);
}

var arr = [1, 3, 7, 4, 5, 6];
console.log(somar(...arr)); // dá 26!

The old-fashioned way would be:

function somar() {
  var soma = 0;
  for (var i = 0; i < arguments.length; i++) {
    soma += arguments[i];
  }
  return soma;
}

var arr = [1, 3, 7, 4, 5, 6];
console.log(somar.apply(null, arr)); // dá 26!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.