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

How to check for last item when looping through a structure in ColdFusion?

我想遍历一个结构并为除最后一项之外的所有项目输出一些内容。对于数组,这可以很容易地通过检查当前索引是否是最后一个索引来完成,但对于结构如何做到这一点?

示例代码:

<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>

循环时增加你自己的 "index":

<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>

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

<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>