JavaScript array.length返回正确的数字,但console.log(数组)为空

时间:2013-02-12 23:01:18

标签: javascript arrays forms

我在这里获取HTML复选框的表单数据:

host1 = document.getElementById("host1").checked;
host2 = document.getElementById("host2").checked;
host3 = document.getElementById("host3").checked;
host4 = document.getElementById("host4").checked;
host1Value = document.getElementById("host1").value;
host2Value = document.getElementById("host2").value;
host3Value = document.getElementById("host3").value;
host4Value = document.getElementById("host4").value;

将空数组附加到已检查的数组并将变量设置为数组长度:

if (host1) {hostsArray.push(host1Value); };
if (host2) {hostsArray.push(host2Value); };
if (host3) {hostsArray.push(host3Value); };
if (host4) {hostsArray.push(host4Value); };
hostsNum = hostsArray.length;

当我将hostNum和hostsArray记录到控制台时,hostNum正确识别已选中复选框的数量,以便阵列报告正确的长度,但数组记录为空。我很茫然。

1 个答案:

答案 0 :(得分:0)

此代码在Chrome中运行良好,您也可以在此JSbin上看到它:http://jsbin.com/eSuwAri/2

我用一个简单的for循环重构它,但它几乎与你的例子相同。我认为问题出在你的js或html代码的其他地方。

HTML:

<input id="host1" type="checkbox" name="host1name" value="host1value">host1 text<br>
<input id="host2" type="checkbox" name="host2name" value="host2value">host2 text<br>
<input id="host3" type="checkbox" name="host3name" value="host3value">host3 text<br> 
<input id="host4" type="checkbox" name="host4name" value="host4value">host4 text<br>               
<button onclick="test()">Click me</button>

Javascript:

    function test(){
        var hostsArray = new Array();
        for (var i=1;i<=4;i++){ 
            var id = "host" + i;
            var checked = document.getElementById(id).checked;
            var value = document.getElementById(id).value;

            if (checked) {
                hostsArray.push(value) 
            };
        }
        hostsNum = hostsArray.length;

        console.log("Array : ")
        console.log(hostsArray);
        console.log("number of value : " +  hostsNum);
    }

控制台输出:

"Array : "
["host1value", "host2value", "host3value", "host4value"]
"number of value : 4"