输入到文本字段的一系列数字的总和和平均值 [英] Sum and Average of a series of numbers inputed to a text field
问题描述
我正在尝试创建一个应用程序,该应用程序计算输入到用空格分隔的文本字段中的数字的总和和平均值.
I am trying to create an application that calculates the sum and average of numbers that are inputted into a text field separated by spaces.
我被困在必须循环放置以根据间隔输入计算总和和平均值的部分.输入代码时,我一直在使用console.log进行测试.
I am stuck on the part where you have to put in a loop to calculate the sum and avg from the spaced inputs. I have been using console.log to test throughout while I type my code.
任何指导都会有所帮助.第一次做javascript.我看了这个网站上的表格,似乎所有的sum/avg javascript问题都基于输入文本.这就是为什么我要提出一个新问题.
Any guidance would be helpful. First time doing javascript. I have looked at the forms on this website and it seems like all the sum/avg javascript questions arent input text based. That is why I am creating a new question.
HTML和Javascript在下面
HTML and Javascript is Below
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
JavaScript
Javascript
function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}
推荐答案
// Here is your function:
/*function calculateSumAverage() {
//grab the input
var numberSeries = document.getElementById("numberSeries").value;
//split it using.split(" ")
var arr = numberSeries.split(" ");
//set sum var to 0
var sum = 0;
//set avg var to 0
var avg = 0;
//loop input array and sum
for (var i=0; i<arr.length; i++){
sum += arr[i];
}
console.log(sum);
//divded by
//calculate avg divided by myarray.length
//output to div
}*/
// Here is a way to do it functionally:
function calculateSumAverage() {
// This is the string that contains the numbers separated by a space.
var inputValue = document.getElementById('numberSeries').value;
var values = inputValue.split(' ')
.map((val) => parseInt(val))
.filter((val) => !isNaN(val));
var sum = values.reduce((currentVal, nextVal) => currentVal + nextVal, 0);
document.getElementById('calculationOutput').innerHTML = `Average: ${sum / values.length}`;
}
<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>
这篇关于输入到文本字段的一系列数字的总和和平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!