我已经实现了这一点,但由于我不熟悉 FOR 循环语句,所以我按照如下所示的方式完成了它! 你能帮我使用 FOR 循环语句缩短这段代码并解释一下它是如何工作的吗?谢谢
这是我的代码:
var inputs = new Array();
inputs["a"] = document.getElementById("a").value;
inputs["b"] = document.getElementById("b").value;
inputs["c"] = document.getElementById("c").value;
inputs["d"] = document.getElementById("d").value;
inputs["e"] = document.getElementById("e").value;
然后我将它们加起来为:
var inputsvalue = inputs["a"] + inputs["b"] + inputs["c"] + inputs["d"] + inputs["e"];
请注意,我正在添加每个输入字段的值并将它们分配给一个变量!
例如,假设输入字段 a、b、c、d、e 的值如下:
1, 2, 3, 4, 5
所以我希望将它们分配给变量“inputsvalue”,例如:
var inputsvalue = "12345";
这就是为什么我这样添加它们的原因!那么有没有其他方法可以做到这一点!在这个例子中,我只有 5 个输入字段,但是如果有大约 100 个输入字段呢!
这道题的目的是了解FOR循环语句在这个例子中是如何工作的!
提前致谢! :)
最佳答案
// Too bad you can't use reduce.
inputs.reduce(function(a,b){
return a.concat(b);
})
// If you could use reduce, you could use map, as well.
var sum= 'abcde'.split('').map(function(itm){
return document.getElementById(itm).value;
}).reduce(function(a, b){
return a.concat(b);
});
alert(sum)
/* New browsers include map and reduce-
you can add them to older browsers,
but it might make your for in loops break,
if you use for in loops to iterate arrays.
*/
if(!Array.prototype.map){
Array.prototype.map= function(fun, scope){
var T= this, L= T.length, A= Array(L), i= 0;
if(typeof fun== 'function'){
while(i< L){
if(i in T){
A[i]= fun.call(scope, T[i], i, T);
}
++i;
}
return A;
}
}
}
if(!Array.prototype.reduce){
Array.prototype.reduce= function(fun, temp, scope){
var T= this, i= 0, len= T.length, temp;
if(typeof fun=== 'function'){
if(temp== undefined) temp= T[i++];
while(i < len){
if(i in T) temp= fun.call(scope, temp, T[i], i, T);
i++;
}
}
return temp;
}
}
关于javascript - 如何将多个值分配给一个数组并将它们相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6006082/