java JSTL c:forEach,递减数循环不可能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3879248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:49:04  来源:igfitidea点击:

JSTL c:forEach, decremental number loop impossible?

javajspforeachjstl

提问by shkim

I want to print decremental numbers like:

我想打印递减数字,如:

<c:forEach var="i" begin="10" end="0" step="-1">
    ... ${i} ...
</c:forEach>

then I got jsp exception:

然后我得到了jsp异常:

javax.servlet.jsp.JspTagException: 'step' <= 0
    javax.servlet.jsp.jstl.core.LoopTagSupport.validateStep(LoopTagSupport.java:459)
    org.apache.taglibs.standard.tag.rt.core.ForEachTag.setStep(ForEachTag.java:60)
    ....

but this answer says it is possible to loop in both ways:

但是这个答案说可以以两种方式循环:

JSTL forEach reverse order

JSTL forEach逆序

What's wrong with me?

我怎么了?

回答by BalusC

I am not sure how the answerer of the other question got it to work, but I can't get it to work here with the reference JSTL implementation.

我不确定另一个问题的回答者是如何让它工作的,但我无法在这里使用参考 JSTL 实现来工作。

Anyway, you can achieve the requirement with following:

无论如何,您可以通过以下方式达到要求:

<c:forEach var="i" begin="0" end="10" step="1">
    ... ${10 - i} ...
</c:forEach>

Or if you'd like to avoid duplication of 10:

或者,如果您想避免重复10

<c:forEach var="i" begin="0" end="10" step="1" varStatus="loop">
    ... ${loop.end - i + loop.begin} ...
</c:forEach>

回答by Giulio Piancastelli

A possible solution, without using the varattribute:

一个可能的解决方案,不使用var属性:

<c:forEach begin="0" end="10" varStatus="loop">
  ${loop.end - loop.count + 1}
</c:forEach>

Note that stepis omitted too, because its default value is 1.

注意 也step被省略了,因为它的默认值是1