我参加了一个入门编码课程,我们刚开始学习javascript。我们的第一个任务是创建一个简单的javascript计算器,它能够计算数字列表的总和,平均值,最大值和最小值。我的老师说,这可以通过各种方式实现,但他推荐了一些名为" for"循环。我在css和html上很不错,但我一直在努力使用javascript。任何帮助将不胜感激。
HTML:
./casperjs --web-security=no test.js >>/dev/stdout
JSS:
<h4>1,3,9,6,5,7,12,32</h4>
<input type="text" id="valueList"><button type="button" id="calculate">Calculate Stats</button>
<br><br>
<H2>Results</H2>
<ul id="results"><!--javascript will write items here--></ul>
答案 0 :(得分:0)
好的,如果给你一个数字列表并想要计算每一个数字,请考虑一下你在逻辑上做什么。
例如,你有一张纸上有一个数字列表,你想知道哪个是最大数字,你要做的是看第一个数字,把它放在脑中,然后继续扫描在列表中,直到找到大于该数字的数字。然后,您将继续扫描列表,直到找到大于该值的数字等,直到您到达列表的末尾。这可以通过像这样的for循环来实现
var maxSeen = value[0];
for (var i = 1; i < valueCount; i++) {
var thisNumber = value[i];
if (thisNumber > maxSeen) {
maxSeen = thisNumber;
}
}
console.log("max", maxSeen);
考虑如何使用笔和纸计算其他每个,然后Google&#34; for循环&#34;看看你是否可以自己实施其余的。没有比学习更好的学习方法了。
答案 1 :(得分:0)
这是答案。
https://jsfiddle.net/5a3bndy9/
$( "#calculate" ).click(processValues);
function processValues() {
var valueSum = 0;
var valueAverage = 0;
var valueMax = 0;
var valueMin = Infinity;
//listens for click event
$("#results" ).html( "" );//clears any list items from last calculation
var valueString = $( "#valueList" ).val();
var value = $.map(valueString.split(","), Number ); //this is an array
valueCount = value.length; //get the lenght of the array (number of values)
//
//Use a loop (or loops) here to help calculate the sum, average, max, and min of the values
//
// loop to find sum
for (var i=0; i <= valueCount; i++)
{
if (value[i] != undefined) // this check exists because your array includes undefined and it shouldn't
{
valueSum += +value[i];
}
}
// praxis to find average
valueAverage = valueSum / valueCount;
// loop to find max
for (var i=0; i <=valueCount; i++)
{
if (value[i] != undefined) // this check exists because your array includes undefined and it shouldn't
{
if (value[i] > valueMax)
{
valueMax = value[i];
}
}
}
//loop to find min
for (var i=0; i <=valueCount; i++)
{
if (value[i] != undefined) // this check exists because your array includes undefined and it shouldn't
{
if (value[i] <= valueMin)
{
valueMin = value[i];
}
}
}
$("#results" ).append( "<li>The values sum is : " + valueSum + ".</li>" );//appends values
$("#results" ).append( "<li>The values average is : " + valueAverage + ".</li>" );//appends values
$("#results" ).append( "<li>The values max is : " + valueMax + ".</li>" );//appends values
$("#results" ).append( "<li>The values min is : " + valueMin + ".</li>" );//appends values
$("#results" ).append( "<li>There are " + valueCount + " values.</li>" );//appends value count
//need to append Sum, average, max, and min to bullet list here
}