Javascript 使用循环收集变量
我会对我已经找到的答案发表评论;但是,我最近创建了一个帐户,没有所需的声誉。答案就在这个链接上: 如果你向下滚动,这是罗布给出的答案。在他的脚本中,他提到可以在循环中收集变量,而不是手动调用变量,但他没有说明如何做到这一点。如果有人能给我一些关于如何做到这一点的见解,我将不胜感激 提前谢谢你,因为我花了将近7个小时试图弄明白这一点 下面是另一页的代码:Javascript 使用循环收集变量,javascript,loops,Javascript,Loops,我会对我已经找到的答案发表评论;但是,我最近创建了一个帐户,没有所需的声誉。答案就在这个链接上: 如果你向下滚动,这是罗布给出的答案。在他的脚本中,他提到可以在循环中收集变量,而不是手动调用变量,但他没有说明如何做到这一点。如果有人能给我一些关于如何做到这一点的见解,我将不胜感激 提前谢谢你,因为我花了将近7个小时试图弄明白这一点 下面是另一页的代码: function calcAvg(one, two, three, four, five) { // Note that t
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
}
根据我对你的任务的理解,你可以通过以下方式使用阵列:
var arr = []
for(int i; i<n; i++)
{
arr[i] = //Whatever the variable must hold
}
var arr=[]
for(int i;i)
在他的脚本中,他提到可以在循环中收集变量,而不是手动调用它们,但他没有说明如何做到这一点
实际上是这样,但分两步进行
calcAvg()
收集数组中的变量,该数组被传递到performCalc()
:
此代码段中的[…]
是一个数组,在本例中,创建一个新的数组,其中5个输入值作为元素
这类似于使用:
performCalc()
然后获取数组
,作为其值
参数传递,并在其上循环:
// 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];
}
//循环值,注意值是字符串,因此
//需要在添加之前转换为数字
对于(var i=0,iLen=values.length;这是对现有答案的注释。@很好地说明了这个问题本可以准备得更好(一方面,另一个问题的代码可以复制过来),但另一个答案不包括这里要寻找的答案。我想说,如果你重新措辞,这个问题可能是有效的。因为它很可能很快就会被关闭。好的,有可能创建一个变量数组,其中while循环限制创建的变量数量吗?唯一的问题是while循环是变量的函数在php中,有没有办法将php变量推送到javascript?@user2618927循环基于数组(iLen=values.length;i)进行操作
var average = performCalc(new Array(one, two, three, four, five));
// 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];
}