javascript总结数组

时间:2010-12-26 15:55:20

标签: javascript

我试图使用javascript对数组中元素的值求和,这是我的脚本。

function sumAll()
{
    var totalOverheads = 0;
    var overheads = new Array();
    overheads = document.getElementsByName('overhead');
    for(i=0;i<overheads.length;i++)
        if(!isNaN(overheads[i].value) || overheads[i].value != null || overheads[i].value != "" || overheads[i].value != '' || overheads[i].value != NULL)
            alert(overheads[i].value);
            //totalOverheads = parseInt(totalOverheads) + parseInt(overheads[i].value);
    alert(totalOverheads);
}

现在,在for循环中的if条件中,我在警报中显示项目的值,但它无法正常工作,它只显示所有项目,即使该项目不是数字,如果输入只是一个数字,我怎么能执行一个操作?

1 个答案:

答案 0 :(得分:1)

getElementsByName返回NodeList。不确定这是不是问题,但无论如何:

var totalOverheads = 0;
var overheads = document.getElementsByName('overhead');
var n;
var i; // <<--- don't forget to initialise i
for (i = 0; i < overheads.length; ++i) {
    n = parseInt(overheads.item(i).value, 10);
    if (!isNaN(n)) {
        totalOverheads += n;
    }
}
alert(totalOverheads);

另外,请使用括号!