我会评论我已经找到的答案;但是,我最近创建了一个帐户,但没有所需的声誉。答案就在这个链接上:
Calculate average of 5 numbers using 2 functions and onchange event handlers
如果向下滚动,这是RobG给出的答案。在他的脚本中,他提到你可以在循环中收集变量而不是手动调用它们,但他没有说明如何做到这一点。如果有人能给我一些关于如何做到这一点的见解,那将非常感激。
先谢谢,因为我花了将近7个小时的时间试图解决这个问题。
这是其他页面的代码:
function calcAvg(one, two, three, four, five) {
// Note that these could be collected using a loop
var one = document.totalf.one.value;
var two = document.totalf.two.value;
var three = document.totalf.three.value;
var four = document.totalf.four.value;
var five = document.totalf.five.value;
// At this point you'd normally validate the values retrieved from
// the form and deal with any junk (remove it, stop processing,
// ask for another value, etc.)
// pass values to performCalc and store result
var average = performCalc([one, two, three, four, five]);
// Now do something with the result
document.totalf.res.value = average;
// There's no need for a return statement as
// the function doesn't need to return a value
// Though an empty return statement is harmless
// return
}
答案 0 :(得分:1)
在他的剧本中,他提到你可以在循环中收集变量而不是手动调用它们,但是他没有说明如何做到这一点。
实际上确实如此,但分两步。
calcAvg()
收集Array
中传递给performCalc()
的变量:
var average = performCalc([one, two, three, four, five]);
此代码段中的[...]
为Array
literal,在这种情况下,会创建一个new
Array
,其中包含5个输入值作为元素。
var average = performCalc(new Array(one, two, three, four, five));
performCalc()
然后获取Array
,作为其values
参数传递,并循环遍历它们:
// Loop over values, note that values are strings so they
// need to be converted to numbers before being added
for (var i=0, iLen=values.length; i<iLen; i++) {
// the unary "+" operator will cooerce the value to a number
// In real life, the value would be checked before being added
// to avoid errors from junk input
sum += +values[i];
}
答案 1 :(得分:0)
根据我对你的任务的理解,你可以通过以下方式使用数组:
var arr = []
for(int i; i<n; i++)
{
arr[i] = //Whatever the variable must hold
}
你可以从输入对象(一,二,三,四,五)中创建一个数组,并在循环中使用它们。