为什么我的阵列未定义的一些值 [英] Why are some values in my array undefined
问题描述
我有一个在PHP中循环,增加了一些看起来像这样我的页面上的复选框
I have a for loop in php that adds a number of checkboxes on my page that look like this
<input type="checkbox" name="checkbox[]">
我想用JavaScript来检查这检查,并在数组中添加值
I want to use javascript to check which is checked and add value in an Array
var cboxes = document.getElementsByName('checkbox[]');
var len = cboxes.length;
var imageArray = new Array();
for (var i = 0; i < len; i++) {
if (cboxes[i].checked) {
imageArray[i] = cboxes[i].value;
}
}
如果我有50箱,并点击复选框号2,4和6,遍历我的数组,我得到的结果。
If I have 50 boxes and click the checkbox number 2,4 and 6, loops through my array, I get the result.
for(var i = 0; i < imageArray.length; i++){
gallery.innerHTML += imageArray[i] + "<br>";
}
-
undefined
Correct value
undefined
Correct value
undefined
Correct value
如果我检查数字1,2,3我得到的结果。
If I check number 1, 2, 3 I get the result
Correct value
Correct value
Correct value
为什么当我跳过一个复选框,我得到了一个未定义?我该如何解决这个问题。
Why do I get undefined when I skip a checkbox? How do I fix it
推荐答案
这是因为你添加额外的元素添加到数组。借此code,例如:
This is because you are adding extra elements to an array. Take this code, for instance:
var a = []; // empty array
a[1] = 'foo'; // don't set a[0]
console.log(a.length); // gives 2
JavaScript就总是填充数组键列表差距。如果你错过了一些列,使用Javascript将填补空白与未定义
。
而不是键名称添加元素阵列,只是推
它到数组的末尾:
Rather than adding the element to your array by the key name, just push
it onto the end of the array:
imageArray.push(cboxes[i].value);
这篇关于为什么我的阵列未定义的一些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!