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[]));
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[]));
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 javascript
You are not signed in. Login or sign up in order to post.
Tell us what your goal is. You’re adding up the two arguments, but passing an array. It’s not clear to me.
– BrTkCa
Document.write(sum(arr[0],arr[1]); it is a possibility ...
– Bruno
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.
– Antonio celso vieira
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; }
– Antonio celso vieira
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.
– Woss
Yeah, you better put the
var
before, always. See https://answall.com/a/2517 and https://answall.com/a/927– bfavaretto
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?
– Sergio