JCCC JavaScript CodePen Quiz 6
Solution for the quiz posted on CodePen.
HTML:
Enter a list of numbers to calculate some statistics.
Count: | |
Sum: | |
Average: | |
Minimum: | |
Maximum: |
JavaScript:
// How do you get the list of numbers from the input box? function getNumbers(inputId) { var input = document.getElementById(inputId); return input.value; } // How do you extract the numbers from // the list? function extractNumbersFromList(list) { if (list === "") { return []; } // Split the list into an array and use // the Array map() function to convert // each element in the array into a number. var listArray = list.split(","); return listArray.map(function (item) { return parseInt(item); }); } // How can you calculate the statistics? function calculateStatistics(numbers) { var stats = { sum: 0, minimum: numbers[0], maximum: numbers[0] }; for (var index = 0; index < numbers.length; ++index) { stats.sum += numbers[index]; stats.maximum = Math.max(stats.maximum, numbers[index]); stats.minimum = Math.min(stats.minimum, numbers[index]); } stats.count = numbers.length; stats.average = stats.sum / stats.count; return stats; } // How do you put the results into the table? function updateCell(id, value) { var cell = document.getElementById(id); cell.innerHTML = value; } function updateCells(stats) { for (var property in stats) { updateCell(property, stats[property]); } } // When do you perform these actions? // (You need something to act as a // trigger.) var numberInput = document.getElementById("number-list"); numberInput.oninput = function(event) { var list = getNumbers(event.target.id); var numbers = extractNumbersFromList(list); var stats = calculateStatistics(numbers); updateCells(stats); };