我正在处理一个需要我计算某些字段的SUM的应用程序。
我的输入是:
in1 = df[0][b];
in2 = df[0][c];
in3 = df[0][f];
total
我将内容作为数组拉出,阵列之间可能存在间隙。例如:
df[1][b] = 123;
df[2][b] = empty or null;
df[3][b] = 456;
df[4][b] = 5567;
公式是:
df[0][f] = df[0][c] / df[0][b];
total = sum of df[0][c];
我已经尝试了以下代码,它工作正常但是当我有GAPS(空或null或NaN)时,计算停止!任何想法?
function updatesum()
{
var kon = 0;
var lenArr = 0;
for (i = 0; i < 1000; i++) {
if(document.forms["sampleform"]["df["+i+"][c]"]) {lenArr++;}
else { break; }
}
var total =0;
for (j = 0; j < lenArr; j++) {
total = total + (document.forms["sampleform"]["df["+j+"][c]"].value-0);
document.forms["sampleform"]["df["+j+"][f]"].value = (document.forms["sampleform"]["df["+j+"][c]"].value-0) / (document.forms["sampleform"]["df["+j+"][b]"].value-0);
}
document.forms["sampleform"]["toplam"].value = total;
document.forms["sampleform"]["kalantutar"].value = total - (document.forms["sampleform"]["odenentutar"].value-0);
}
答案 0 :(得分:1)
你需要使用parseFloat或parseInt然后删除if语句中的break
...
您可以像这样使用它
!isNAN(document.forms["sampleform"]["df["+j+"][f]"].value)? document.forms["sampleform"]["df["+j+"][f]"].value :0
或检查该值是否为假值,然后按照document.forms["sampleform"]["df["+j+"][f]"].value||0
这是完整的源代码
function updatesum(){
var kon = 0;
var lenArr = 0;
for (i = 0; i < 1000; i++) {
if(document.forms["sampleform"]["df["+i+"][c]"]) {lenArr++;}
//else { break; }
}
var total =0;
for (j = 0; j < lenArr; j++) {
total = total + (document.forms["sampleform"]["df["+j+"] [c]"].value-0);
document.forms["sampleform"]["df["+j+"][f]"].value =
(document.forms["sampleform"]["df["+j+"][c]"].value||0) /
(document.forms["sampleform"]["df["+j+"][b]"].value||1);
}
document.forms["sampleform"]["toplam"].value = total;
document.forms["sampleform"]["kalantutar"].value =
total - (document.forms["sampleform"]["odenentutar"].value||0);
}
答案 1 :(得分:0)
我解决了问题:
function updatesum(ele)
{
var kon = 0;
lenArr = new Array;
for (i = 0; i < 1000; i++) {
if(document.forms["sampleform"]["df["+i+"][c]"]) {lenArr[i] = 1;}
else {lenArr[i] = 0; }
}
var total =0;
for (j = 0; j < lenArr.length; j++) {
if(lenArr[j] === 1){
total = total + (document.forms["sampleform"]["df["+j+"][c]"].value-0);
document.forms["sampleform"]["df["+j+"][f]"].value = (document.forms["sampleform"]["df["+j+"][c]"].value-0) / (document.forms["sampleform"]["df["+j+"][b]"].value-0);
}
}
document.forms["sampleform"]["toplam"].value = total;
document.forms["sampleform"]["kalantutar"].value = total - (document.forms["sampleform"]["odenentutar"].value-0);
}