【问题标题】:ColdFusion: Is it possible to get the index from a cfscript for in loop?ColdFusion:是否可以从 cfscript for in 循环中获取索引?
【发布时间】:2017-10-24 21:19:23
【问题描述】:

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

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

非常简单,我要做的是在 for in 循环中获取当前索引并将其传递给函数:processStruct(item, index)。我知道我可以使用常规的 for 循环来做到这一点,标签版本 <cfloop>

也可以做到这一点
<cfloop array="#myArray#" index="i">
    #i#
<cfloop>

【问题讨论】:

    标签: coldfusion cfml


    【解决方案1】:

    标签变体&lt;cfloop&gt; 提供从 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 --->
    

    2016 年之前的所有 ColdFusion 版本都没有,因此您必须自己完成:

    <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's Iterator interface 也不提供。

    【讨论】:

    • cfloop 的脚本变体支持 Lucee 中的索引:trycf.com/gist/b60987764fb9ba9f2292ba2fbdd48e91/…
    • 我指的是开始帖子中提到的for(x in a) 脚本变体。您刚刚展示了 cfloop 标记的 cfscript 版本。
    • 啊,你可能想编辑你的答案。不清楚您指的是哪个“脚本变体”。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 要么 idx 应该从 0 开始,要么循环中的两行顺序错误。
      • 对吗?我想这就是半夜发生的事情。谢谢提醒。
      • 您也可以删除idx++; 行,如果idx = 1,则使用processStruct( item, idx++ );,如果idx = 0,则使用processStruct( item, ++idx );
      【解决方案4】:

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

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

      【讨论】:

      • 问题的最后一句表示他已经知道如何使用这种方法。因此投反对票。
      猜你喜欢
      • 2012-08-20
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多