I have some values that come randomized to an variable.
Now i want to add every value to each other to get an total sum but the loop wont add them together.
The index variable work when i console log it. but not the total sum of a current value and the index value.
Any tips ?
This is the loop
// The indexValue is values I get from an array//
var indexValue = index; // Random number from 1 - 10
var totalSum = 0;
for(var x = 0; x <indexValue; x++){
var currentValue = index[x];
totalSum += currentValue;
}
console.log(totalSum);
I’m assuming since you’re referencing
index[x]thatindexis an array. If so, you are assigning the wrong value toindexValue. Try this:What this does is assign the length of the array to the variable
indexValue. Now theforloop will run from 0 to n where n is the length of the array.This should get you the values you need.
Hope this helps.
EDIT:
Below is a link to a jsFiddle I created with your example and the code explained:
jsFiddle
The code above is a modified version of what you posted. The current value is not needed and has been removed. In this case, I created an array and stored the values in index. The length is computed, and the values are added together.
For the easy sake of testing, I changed
console.log(totalSum);toalert(totalSum);. It will produce the same value just the same.Just a reference note on
console.log. Some browsers (mainly IE) who do not attach the debugger to the process automatically without a page refresh will through an error asconsolewill beundefined. Here is a quick fix for that:This checks that (a) the console object is attached to the global window object and (b) that the log object of console is attached to the console object.