我在迭代和获取数组集合中的值时遇到了麻烦(我想是一个数组数组)
我希望下面的代码会显示一个警报,依次显示每个数组的3个值(例如“婴儿”,“0”和“2”),但警报只显示“0”“未定义” ,undefined“。
我错过了什么?
声明数组:
var ageGroups = [["infant", 0, 2], ["child", 3, 18], ["child", 3, 17], ["adult1", 18, 64], ["adult2", 65, 74], ["adult3", 75, 79]];
迭代数组
for (var item in ageGroups) {
alert(item[0]);
alert(item[1]);
alert(item[2]);
}
答案 0 :(得分:4)
使用console.log
代替警报,警报将仅显示[对象],如果变量是对象,但在控制台中您可以看到什么类型的对象,您可以进一步调试
for (var item in ageGroups) {
console.log(ageGroups[item][0]);
console.log(ageGroups[item][1]);
console.log(ageGroups[item][2]);
}
答案 1 :(得分:1)
for (var item in ageGroups) {
alert(ageGroups[item][0]);
alert(ageGroups[item][1]);
alert(ageGroups[item][2]);
}
答案 2 :(得分:1)
你的问题是该项是你的数组的关键试试这个:
for (var item in ageGroups) {
alert(ageGroups[item][0]);
alert(ageGroups[item][1]);
alert(ageGroups[item][2]);
}
答案 3 :(得分:1)
使用该死的forEach
! :-)虽然不是跨浏览器,但是垫片很容易实现。
// Call forEach and define the callback function
ageGroups.forEach(loopArray)
// Now let's work with the array!
function loopArray(ageGroup) {
console.log(ageGroup[0])
console.log(ageGroup[1])
console.log(ageGroup[2])
}
答案 4 :(得分:0)
不要使用for in
在JavaScript中迭代数组。其目的是迭代对象属性。而是使用增量for循环..
for (var i=0; i<ageGroups.length; i++) {
for (var j=0; j<ageGroups[i].length; j++) {
console.log(ageGroups[i][j]);
}
// Or instead of an inner loop access them individually
console.log(ageGroups[i][0]);
console.log(ageGroups[i][1]);
console.log(ageGroups[i][2]);
}
在数组上使用for-in
构造可能会产生与增量循环截然不同的结果,例如,如果您只定义了一个数组项myArr[3] = 123;
。在这种情况下,JavaScript将分配项目0-2,for循环将迭代它们,但for-in
不会。更重要的是,外部脚本和框架可以扩展Array原型并添加属性,当您真正想要数组元素时,这些属性将突然包含在for-in
迭代器中。
答案 5 :(得分:0)
你应该做
for (i = 0; i <ageGroups.length; i++) {
var item = ageGroups[i];
alert(item[0]);
alert(item[1]);
alert(item[2]);
}
javascript中的 for..in
用于迭代对象的属性
答案 6 :(得分:0)
这是一个优化的for
循环,我在这里存储长度,所以它不会在每次迭代时进行评估:
for (var i = 0, l = ageGroups.length; i < l; i++){
alert(ageGroups[i][0]);
alert(ageGroups[i][1]);
alert(ageGroups[i][2]);
}
使其与您的示例完全相同,您可以将ageGroup的迭代存储在变量中:
for (var i = 0, l = ageGroups.length, item; i < l; i++){
item = ageGroups[i];
alert(item[0]);
alert(item[1]);
alert(item[2]);
}