如何循环访问另一个数组中每个数组的每个成员?
假设有一个数组的数组。
n = [ a = ["foo","bar"],
b = ["foo2","bar2"],
c = ["foo3","bar3"],
d = ["foo4","bar4"],
e = ["foo5","bar5"] ]
循环所有 foo
和 bar
的最简单语法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果按照您的示例,内部数组中总是有 2 个东西(小提琴 - http://jsfiddle.net/pvqtz/ ):
对于任意数量的事物,使用嵌套循环(fiddle - http://jsfiddle.net/pvqtz/1/):
If you always have exactly 2 things in the inner arrays as per your example (fiddle - http://jsfiddle.net/pvqtz/):
For an arbitrary number of things, use a nested loop (fiddle - http://jsfiddle.net/pvqtz/1/):
如果你的环境支持它,我倾向于使用
forEach
来实现这一点:而且,如果你正在处理任意深度的嵌套数组,你可以递归:
If your environment supports it, I tend to like
forEach
for this:and just for the heck of it, if you're dealing with nested arrays of arbitrary depth, you can recurse:
要在一个循环中迭代 foos 和 Bars:
或
要迭代所有 foos,then 迭代所有 Bars:
或
To iterate over foos and bars in one loop:
or
To iterate over all foos, then over all bars:
or