我有一个ArrayList我想完全输出为String.基本上我想按顺序输出它,使用toString由制表符分隔的每个元素.有没有快速的方法来做到这一点?你可以循环它(或删除每个元素)并将它连接到一个字符串,但我认为这将是非常缓慢的.
每隔一段时间,无论是在显示代码中还是在组装字符串中,我都会制作一个列表并需要弄清楚如何在该列表中插入逗号.
这就是我通常这样做的方式:
<cfset hide_comma=true>
<cfloop ... some kind of loop ...>
<cfif hide_comma><cfset hide_comma=false><cfelse>,</cfif>
.... rest of code here ...
</cfloop>
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更清洁的方法.我意识到一个选项将类似于以下内容:
<cfset output_as_array = []>
<cfloop ... some kind of loop ...>
<cfset loop_output = "">
... rest of code here, but append all output to loop output instead ...
<cfset ArrayAppend(output_as_array, trim(loop_output))>
</cfloop>
<cfoutput>#ArrayToList(output_as_array, ", ")#</cfoutput>
Run Code Online (Sandbox Code Playgroud)
但这似乎并不是更清楚.
相比之下,在Django中,每个循环都有一个内置计数器,所以我可以编写如下内容:
{% for ... some kind of loop ... %}
{% if not forloop.first %},{% endif %}
... rest of code …Run Code Online (Sandbox Code Playgroud)