如何迭代数组数组

时间:2021-07-25 14:26:52

What's the best way to iterate over an array of arrays?

迭代数组数组的最佳方法是什么?

sounds = [ [Name_1, link_1], [Name_2, link_2], [Name_3, link_3], [Name_4, link_4] ]

I want to the output in HTML ul/li structure:

我想在HTML ul / li结构中输出:

<ul>
   <li>Name_1, link_1</li>
   <li>Name_2, link_2</li>
   <li>Name_3, link_3</li>
   <li>Name_4, link_4</li>
</ul>

3 个解决方案

#1


37  

Assuming all the inner arrays have fixed size, you can use auto-unpacking to get each item of the inner array in its own variable when iterating over the outer array. Example:

假设所有内部数组都具有固定大小,则可以在迭代外部数组时使用自动解包来获取内部数组的每个项目在其自己的变量中。例:

sounds.each do |name, link|
  # do something
end

#2


3  

In view:

在视图中:

<ul>
  <% sounds.each do |sound| %>
    <li> <%=h sound.join ', ' %></li>
  <% end %>
</ul>

#3


1  

Use a nested loop. The outer one iterates over sounds, while the inner one iterates over the current element from sounds.

使用嵌套循环。外部迭代声音,而内部声音迭代声音中的当前元素。

Of course, in that particular example, it would probably be easiest just to directly reference the elements of the inner arrays. That way, you could just print <li>$inner[0], $inner[1]</li> (note that I've never used Ruby, so I don't know how arrays are indexed, let alone printing syntax).

当然,在该特定示例中,直接引用内部数组的元素可能是最简单的。这样,你可以打印

  • $ inner [0],$ inner [1] (注意我从未使用过Ruby,所以我不知道数组是如何编入索引的,更不用说打印语法了)。

  • $ inner [0],$ inner [1](注意我从未使用过Ruby,所以我不知道数组是如何编入索引的,更不用说打印语法了)。
  • #1


    37  

    Assuming all the inner arrays have fixed size, you can use auto-unpacking to get each item of the inner array in its own variable when iterating over the outer array. Example:

    假设所有内部数组都具有固定大小,则可以在迭代外部数组时使用自动解包来获取内部数组的每个项目在其自己的变量中。例:

    sounds.each do |name, link|
      # do something
    end
    

    #2


    3  

    In view:

    在视图中:

    <ul>
      <% sounds.each do |sound| %>
        <li> <%=h sound.join ', ' %></li>
      <% end %>
    </ul>
    

    #3


    1  

    Use a nested loop. The outer one iterates over sounds, while the inner one iterates over the current element from sounds.

    使用嵌套循环。外部迭代声音,而内部声音迭代声音中的当前元素。

    Of course, in that particular example, it would probably be easiest just to directly reference the elements of the inner arrays. That way, you could just print <li>$inner[0], $inner[1]</li> (note that I've never used Ruby, so I don't know how arrays are indexed, let alone printing syntax).

    当然,在该特定示例中,直接引用内部数组的元素可能是最简单的。这样,你可以打印

  • $ inner [0],$ inner [1] (注意我从未使用过Ruby,所以我不知道数组是如何编入索引的,更不用说打印语法了)。

  • $ inner [0],$ inner [1](注意我从未使用过Ruby,所以我不知道数组是如何编入索引的,更不用说打印语法了)。