[英]JavaScript array.length returning correct number, but console.log(array) empty
I'm getting form data for HTML check boxes here: 我在这里获取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;
Appending to an empty array those which are checked and setting a variable to the array length: 将检查的内容附加到空数组并将其设置为数组长度:
if (host1) {hostsArray.push(host1Value); };
if (host2) {hostsArray.push(host2Value); };
if (host3) {hostsArray.push(host3Value); };
if (host4) {hostsArray.push(host4Value); };
hostsNum = hostsArray.length;
When I log hostNum and hostsArray to the console, hostNum correctly identifies the number of checked boxes so the array is reporting the correct length, but the array logs as empty. 当我将hostNum和hostsArray登录到控制台时,hostNum可以正确标识复选框的数量,因此该阵列报告正确的长度,但是该阵列记录为空。 I'm at a loss.
我很茫然。
This code work fine in Chrome, you can also see it on this JSbin : http://jsbin.com/eSuwAri/2 这段代码在Chrome中运行良好,您也可以在以下JSbin上看到它: http ://jsbin.com/eSuwAri/2
I have refactor it with a simple for loop, but it's almost the same as your example. 我已经用一个简单的for循环重构了它,但是它与您的示例几乎相同。 I presume the problem is elsewhere in your js or html code.
我认为问题出在您的js或html代码中的其他地方。
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 : 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);
}
Console output: 控制台输出:
"Array : "
["host1value", "host2value", "host3value", "host4value"]
"number of value : 4"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.