循环遍历ColdFusion中的结构时如何检查最后一项?

时间:2017-07-07 06:36:39

标签: coldfusion lucee

我想循环一个结构并输出除最后一个项目之外的所有项目。对于数组,可以通过检查当前索引是否是最后一个索引来轻松完成,但如何对结构执行此操作?

示例代码:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <!--- Here should be the conditional output --->
</cfloop>
</cfoutput>

2 个答案:

答案 0 :(得分:4)

循环时只需递增自己的“索引”:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
thisItemNumber = 1;
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <cfset thisIsNotTheLastItem = ( thisItemNumber LT totalItems )>
    <cfif thisIsNotTheLastItem>
        is not the last item<br/>
    </cfif>
    <cfset thisItemNumber++>
</cfloop>
</cfoutput>

编辑:这是使用数组的替代方法

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
totalItems = StructCount( myStruct );
keys = StructKeyArray( myStruct );
lastItem = myStruct[ keys[ totalItems ] ];
</cfscript>
<cfoutput>
<cfloop array="#keys#" item="key">
    #myStruct[ key ]#
    <cfif myStruct[ key ] IS NOT lastItem>
        is not the last item<br/>
    </cfif>
</cfloop>
</cfoutput>

答案 1 :(得分:1)

这将是一个简单的解决方案。

<cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
   };
</cfscript>
<cfset KeyListArray = ListToArray(StructKeyList(myStruct))>
<cfoutput>
    <cfloop from="1" to="#(ArrayLen(KeyListArray)-1)#" index="i"> 
       #myStruct[i]#
      <!--- Here should be the conditional output --->
    </cfloop>
</cfoutput>