JSTL forEach逆序 [英] JSTL forEach reverse order
问题描述
使用JSTL的 forEach
标记,是否可以按相反的顺序迭代?
Using JSTL's forEach
tag, is it possible to iterate in reverse order?
推荐答案
当你使用 forEach
创建一个整数循环时,你可以前进或后退,但它需要一些工作。事实证明你不能这样做,例如:
When you are using forEach
to create an integer loop, you can go forward or backward, but it requires some work. It turns out you cannot do this, for example:
<c:forEach var="i" begin="10" end="0" step="-1">
....
</c:forEach>
因为规范要求步骤为正。但是你总是可以按顺序循环,然后使用< c:var
将递增的数字转换为递减的数字:
because the spec requires the step is positive. But you can always loop in forward order and then use <c:var
to convert the incrementing number into a decrementing number:
<c:forEach var="i" begin="0" end="10" step="1">
<c:var var="decr" value="${10-i}"/>
....
</c:forEach>
但是,当您执行 forEach
时通过任何类型的集合,我不知道有任何方法使对象的顺序相反。至少,不是先将元素排序为相反的顺序,然后然后使用 forEach
。
However, when you are doing a forEach
over a Collection of any sort, I am not aware of any way to have the objects in reverse order. At least, not without first sorting the elements into reverse order and then using forEach
.
我已成功通过在JSP中执行以下操作,以所需顺序导航 forEach
循环:
I have successfully navigated a forEach
loop in a desired order by doing something like the following in a JSP:
<%
List list = (List)session.getAttribute("list");
Comparator comp = ....
Collections.sort(list, comp);
%>
<c:forEach var="bean" items="<%=list%>">
...
</c:forEach>
使用合适的比较器,您可以按任何所需顺序循环遍历项目。这很有效。但我不知道如何简单地说,以相反的顺序迭代所提供的集合。
With a suitable Comparator, you can loop over the items in any desired order. This works. But I am not aware of a way to say, very simply, iterate in reverse order the collection provided.
这篇关于JSTL forEach逆序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!