简体   繁体   English

计算Javascript中数组元素的平均值

[英]Calculate the average of array elements in Javascript

I got this Javascript exercise.我得到了这个 Javascript 练习。 The average should be 11.2, but my program returned 5420502.4.平均值应该是 11.2,但我的程序返回了 5420502.4。


Define an empty array.定义一个空数组。 Also create two functions:同时创建两个函数:

addNumber() reads a value from a text input field on the HTML document (id="num") and adds it at the end of the array. addNumber() 从 HTML 文档 (id="num") 的文本输入字段中读取一个值,并将其添加到数组的末尾。

printInfo() outputs the amount of elements in the array to the console, then the average of their values. printInfo() 将数组中元素的数量输出到控制台,然后是它们的平均值。

The HTML document has two buttons for calling the functions. HTML 文档有两个调用函数的按钮。


 var arr = []; function addNumber() { var num = document.getElementById("num").value; return arr.push(num); } function printInfo() { var len = arr.length; console.log("The array has " + len + " elements."); var total = 0; for (var i = 0; i < len; i++) { total += arr[i]; // replace arr[i] with +arr[i] } var avg = total / len; // additionally render result to UI document.getElementById("info").innerText = avg; return console.log("The average of the values is " + avg); }
 .outerStyle { border: 2px solid black; width: 45%; }.inpStyle { padding: 10px; margin: 10px; } button { margin: 10px; }
 <div id="outer" class="outerStyle"> <div class="inpStyle"> <label for="num">Enter number: </label> <input id="num" type="number" /> </div> <button id="addBtn" onclick="addNumber()">Add</button> <button id="printInfo" onClick="printInfo()">Print Info</button> <hr/> <div id="info" /> </div>

The value from your input is a string.输入的值是一个字符串。 So, it will concatenate in to total .因此,它将连接到total If your input value was 1 and you added it to the array twice, your array would consist of 2 strings, "1" and "1".如果您的输入值为 1 并且您将它添加到数组中两次,则您的数组将包含 2 个字符串,“1”和“1”。 Then, you're adding this, which makes "11" because you're adding strings together.然后,您添加这个,这就是“11”,因为您将字符串添加在一起。

You'll want to use something like parseInt to convert the string to a number first.您需要先使用parseInt之类的方法将字符串转换为数字。

function addNumber() {
    var num = document.getElementById("num").value;
    return arr.push(parseInt(num));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM