How do I loop through each member of each array in another array?
Say there's an array of arrays.
n = [ a = ["foo","bar"],
b = ["foo2","bar2"],
c = ["foo3","bar3"],
d = ["foo4","bar4"],
e 开发者_运维技巧= ["foo5","bar5"] ]
What's the simplest syntax to loop through all the foo
s and bar
s?
If you always have exactly 2 things in the inner arrays as per your example (fiddle - http://jsfiddle.net/pvqtz/):
for (var index = 0; index < n.length; index++) {
var foobar = n[index];
var foo = foobar[0];
var bar = foobar[1];
alert(foo + bar);
}
For an arbitrary number of things, use a nested loop (fiddle - http://jsfiddle.net/pvqtz/1/):
for (var index = 0; index < n.length; index++) {
var innerArray = n[index];
for (var innerIndex = 0; innerIndex < innerArray.length; innerIndex++) {
var elem = innerArray[innerIndex];
alert(elem);
}
}
If your environment supports it, I tend to like forEach
for this:
n.forEach(function(n2) {
n2.forEach(function(val) {
console.log(val)
})
});
and just for the heck of it, if you're dealing with nested arrays of arbitrary depth, you can recurse:
function visit(a, f) {
if (Array.isArray(a)) {
a.forEach(function(a2) {
visit(a2, f)
})
} else f(a);
}
n = ["foo",["foo1", "bar1"], ["foo2", ["foo3","bar3"]]];
visit(n, function(val) { console.log(val) });
To iterate over foos and bars in one loop:
var i = -1;
while (i++ < n.length)
alert (n[i][0]+":"+n[i][1]);
or
for (var i = 0; i < n.length; i++)
alert (n[i][0]+":"+n[i][1]);
To iterate over all foos, then over all bars:
var i = -1, j = -1;
while (i++ < 2)
while (j++ < n.length)
alert (n[j][i]);
or
for (var i = 0; i < 2; i++)
for (var j = 0; j < n.length; j++)
alert (n[j][i]);
精彩评论