为什么我的数组中的某些值未定义 [英] Why are some values in my array undefined
问题描述
我在php中有一个for循环,在我的页面上添加了一些看起来像这样的复选框
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
推荐答案
这是因为您要向数组中添加额外的元素。以此代码为例:
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将用 undefined
填写空白。
Javascript will always "fill in" gaps in the list of array keys. If you miss some out, Javascript will fill in the blanks with undefined
.
而不是将元素添加到你的数组按键名称,只需将
推送到数组的末尾:
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屋!