I've already implemented this, but as I'm not familiar with the FOR loop statement I've done it this way as shown below! Can you please help me shorten this code using the FOR loop statement and explain me how this works! Thanks
Here is my code:
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;
And then I've added them up as:
var inputsvalue = inputs["a"] + inputs["b"] + inputs["c"] + inputs["d"] + inputs["e"];
Note that I'm adding the value of each input field and assigning them into a variable!
For example lets say the values for input fields a, b, c, d, e are as follows:
1, 2, 3, 4, 5
So I want them to be assigned to the variable "inputsvalue" like:
var inputsvalue = "12345";
That's why I added them like that! So is t开发者_Python百科here any other way to do this! In this example I only have 5 input fields, but what if there was about 100 input fields!
The purpose of this question is to learn how FOR loop statement works in this example!
Thanks in advance! :)
// 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;
}
}
var inputsValue = "";
for (var i = 0; i < inputs.length; i++){
inputsValue += inputs[i];
}
You can use
var elems = document.getElementsByTagName("input");
var sum = '';
for(i=0; i<elems.length; i++) {
sum = sum + elems[i].value;
}
alert(sum); // to check your result
A better way to do this is to name each input's id something like: id="element0"
, or generally: id="element<n>"
This way you could go:
var sum = 0;
for (i=0; i<max; i++){
var elements = document.getElementById("element" + i);
sum += Number(elements.value);
}
精彩评论