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[]));
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[]));
To pass an array and "distribute" its elements through the arguments of a function you can do it in different ways.
You can do "by hand", as you have in the question and that should be avoided because it is not flexible. Or you can use .apply()
or the modern ES6 way.
Using .appy()
you can pass the array as the second method argument:
var res = soma.apply(null, arr):
Using ES6 spread arguments syntax ) is even simpler and you only use ...
before the array:
var res = soma(...arr):
Both methods do what you want. Then inside the function, if you do not have a fixed number of arguments you can use the reserved word arguments
that inside the function gives you access to all the arguments. It is not an array, but almost, you can convert it 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 way would look like this:
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!
You can do this:
function somarArr (arr1, arr2) {
var result = [];
var i = arr1.length > arr2.length ? arr1.length : arr2.length;
var isArray1 = arr1.length > arr2.length ? true : false;
for (var z = 0; z < i; z++) {
if (isArray1) {
if (!arr2[z]) {
result.push(arr1[z] + 0);
continue;
}
result.push(arr1[z] + arr2[z]);
continue;
}
if (!arr1[z]) {
result.push(arr2[z] + 0);
continue;
}
result.push(arr2[z] + arr1[z]);
continue;
}
return result;
}
var arr1 = [8, 6, 1, 0, 6];
var arr2 = [5, 4, 3, 2];
var text = somarArr(arr1, arr2);
document.write(text.join(' | '));
You can pass two arrays as a parameter. If the number of values in one of them is greater than in another, the script will add 0 in the array with less values.
To use: somarArr(arr1, arr2);
.
Make sure the two parameters are arrays!