Sum and Average of a series of numbers inputed to a text field

左心房为你撑大大i 提交于 2019-12-12 19:20:53

问题


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.

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.

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 and Javascript is Below

<body>
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>
</body>

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
}

回答1:


// 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>



回答2:


You code is fine except sum += parseInt(arr[i]); you need to parse each string input to integer




回答3:


input type="text" will give a string.Also to split this string ,use var arr = numberSeries.split(""); , note there is no space between the quotes. To convert each string to number use unary operator.

sum += +arr[i]; The plus(+) sign before arr[i] will convert a string to number.Unless you convert to number , the string concatenation will produce like this 0123...

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;
  console.log(arr)
  //loop input array and sum
  for (var i = 0; i < arr.length; i++) {
    sum += +arr[i];
  }
  console.log(sum);
}
<input type="text" id="numberSeries" />
<button id="calculateSumAverage" onclick="calculateSumAverage();">Calculate</button>
<div id="calculationOutput"></div>



回答4:


Try like this

function calculateSumAverage() 
{
	var numberSeries = document.getElementById("numberSeries").value;
	var arr = numberSeries.split("");
	var sum = 0;
	var avg = 0;
	for (var i = 0; i < arr.length; i++) 
	{
		sum += parseInt(arr[i]);
	}
}


来源:https://stackoverflow.com/questions/48820525/sum-and-average-of-a-series-of-numbers-inputed-to-a-text-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!