ColdFusion:在cfscript的for循环中,是否有可能获取索引?

3

所以我正在使用for-in循环遍历一个结构体数组

for(item in array) {
    processStruct(item)
}

很简单,我想做的是获取for in循环的当前索引,并将其同时传递到函数processStruct(item, index)中:

。 我知道我可以使用常规for循环来执行此操作,并且使用标记版本<cfloop>也是可能的。

<cfloop array="#myArray#" index="i">
    #i#
<cfloop>
4个回答

4
标签变体<cfloop>提供了item和index,从ColdFusion 2016(或Railo/Lucee)开始可用。
<cfset x = [ "a", "b", "c" ]>
<cfloop array="#x#" index="idx" item="it">
    <cfoutput>#idx#:#it#</cfoutput>
</cfloop>
<!--- returns 1:a 2:b 3:c --->

所有 ColdFusion 版本在 2016 年之前都不支持,因此您必须自己完成:

<cfset x = [ "a", "b", "c" ]>
<cfset idx = 1>
<cfloop array="#x#" index="it">
    <cfoutput>#idx#:#it#</cfoutput>
    <cfset idx++>
</cfloop>
<!--- returns 1:a 2:b 3:c --->

脚本变体不支持此功能,很可能永远不会。Java的迭代器接口也没有提供它。

cfloop的脚本变体在Lucee中支持索引: https://trycf.com/gist/b60987764fb9ba9f2292ba2fbdd48e91/lucee5?theme=monokai - Brad Wood
我指的是起始帖中提到的for(x in a)脚本变体。你只展示了CFLOOP标签的CFSCRIPT版本。 - Alex
啊,你可能想要编辑你的回答。不清楚你指的是哪个“脚本变量”。 - Brad Wood

2

不,你在 for ... in 循环中没有索引。只需设置自己的索引:

var idx = 1;
for( item in struct ){
    processStruct( item, idx );
    idx++;
}

idx 应该从 0 开始,或者循环中的两行代码顺序错误。 - Dan Bracuk
对吧?我猜这就是深夜发生的事情。谢谢你提醒我。 - Robert Munn
如果 idx = 1,你也可以删除 idx++; 这行代码,使用 processStruct( item, idx++ ); 或者如果 idx = 0,使用 processStruct( item, ++idx ); - isapir

2

从CF11开始,您可以使用成员函数。这样您就可以访问元素和索引:

myArray = ["a", "b", "c"];
// By arrayEach() member function CF11+
myArray.each(function(element, index) {
    writeOuput(element & " : " & index);
});

0

尝试这个(其中 i 是您的数组索引):

for (i=1; i lte ArrayLen(yourArray); i++){
     processStruct(yourArray[i],i);
}

问题的最后一句话说他已经知道如何使用这种方法。因此才会被踩。 - Dan Bracuk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接