Goal: Gather all the results from a loop (that loops through JSON object array) and add those values together to produce the overall number of credits for a user. Every time they take a course, they receive credit, but right now, I need to figure out how to add them together. I am new to Javascript and am trying to figure out how to create a function that continually updates (via a for loop), so that I can produce it via HTML in the web page.
I was looking at this stack example that loops together values (for a game) and tried to mimic it. I was also looking at the for loop example via this JS tutorial.
var sum = 0; for (var i = 1; i <= 50; i++) { sum = sum + i; }
alert("Sum = " + sum); // => Sum = 1275
It consists of three parts, separated by semicolons. The first is the initializer (var i = 1) which initializes the loop and is executed only once at the start. The second is a test condition (i <= 50). When a conditional expression evaluates to true, the body of the loop is executed. When false, the loop terminates. The third part is an updater (i++) which is invoked after each iteration. The updater typically increments or decrements the loop counter.
My Code:
//Function that returns HTML for successfully retrieved results
function resultsHTML(JSONResponseObjectArray) {
var ddObjectArray = JSONResponseObjectArray;
var resultString = '';
//Loop through JSON Object Array
for(eeIndex in ddObjectArray) {
var creditHours = ddObjectArray[eeIndex].creditHours;
resultString += ceHTML(creditHours);
console.log("credit hours: " + creditHours);
}
}
function addCredits(){
var result = 0;
for (var i = 0; i <= 0; i++){
result = creditHours + i;
}
return result;
console.log('new results ' + result);
}
Output of Array (via console):
credit hours: null
list.js:114 credit hours: 4
list.js:114 credit hours: 6
list.js:114 credit hours: null
list.js:114 credit hours: 4
list.js:114 credit hours: null
addCreditsfunction is inside of your other function. Second,resultsHTMLisn't closed. Third, yourconsole.logwon't happen because it's after areturnwhich ends the function.