Reputation: 23
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.
I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc([0],[1]);
alert("The total is " + total);
Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"
Thanks
Upvotes: 2
Views: 343
Reputation: 131324
You don't specify the array but only indexes :
var total = simpleCalc([0],[1]);
So, it passes two array objects : [0]
and [1]
.
The concatenation of them here :
var result = a + b;
has as result the 01
String.
To pass the two first elements of myArray
, try it :
var total = simpleCalc(myArray[0],myArray[1]);
Upvotes: 1
Reputation: 3598
You have two options:
You need to pass reference to your array elements like so (myArray[0], myArray[1])
sumValuesInArray()
, pass an array
and calculate all values inside an array using for
loop.See working example here:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc(myArray[0],myArray[1]);
//alert("The total is " + total);
// OR
function sumValuesInArray(array) {
var total = 0;
for(i = 0; i < array.length; i++) {
var element = array[i];
total += element;
}
return total;
}
console.log(sumValuesInArray(myArray));
Upvotes: 5
Reputation: 25810
You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.
It should be:
var total = simpleCalc(myArray[0],myArray[1]);
Upvotes: 0