【问题标题】:ColdFusion - Collection loop in cfscriptColdFusion - cfscript 中的收集循环
【发布时间】:2013-05-08 22:44:22
【问题描述】:

我有一些适用于 Railo 的基于标签的语法。

<cfloop collection="#myArray#" item="j" index="i"></cfloop>

上面允许我访问索引“i”和项目本身,“j”。

我想在cfscript中做同样的事情,所以我使用了:

for ( i in myArray) {}

但是,'i' 给了我 item...如何访问 index 值?

作为一种变通方法,我不得不像这样手动计算索引:

j = 1;
for ( i in myArray) {
j++;
}

但这感觉很脏。 cfscript 的 for in 语法是否允许真正替代 cfloop 的集合?

我已尝试在 Google 上搜索所有这些内容,但从未得到任何体面的结果。有没有办法重写我的 for in 循环以允许我也访问索引?

谢谢, 米奇。

【问题讨论】:

    标签: coldfusion railo cfml


    【解决方案1】:

    恐怕在 ColdFusion 中 是不可能的,除了您当前使用的解决方法,或者只是使用索引 for 循环。

    但是在 Railo 中,有这样的(相当糟糕的标签/脚本混合语法):

    <cfscript>
        loop array=[5,4,3,2,1] index="i" item="v"  {
            writeOutput("[#i#][#v#]<br>");
        }   
    </cfscript>
    

    所以基本上它是不带尖括号的&lt;cfloop&gt;

    【讨论】:

    • 真可惜!我希望在这种语法中有一种优雅的方法,但我的怀疑似乎是正确的。感谢您的回答。
    • NP。顺便说一句,您使用的 CFLOOP 语法是 Railo only。它在 CF 中无效。您可能想更新您的文字。
    • 这就是我的问题。我认为 Railo 使用标签实现了(一种相当不错的)方法,但觉得有必要在其脚本版本中遵守 ACF。无赖!我还编辑了我的帖子以纠正我的错误陈述。
    【解决方案2】:

    在 CF 10 和 Railo 4 中,您可以使用 Underscore.cfc library

    _ = new Underscore();// instantiate the library
    
    _.each(myArray, function(item, index) {
       // code here
    });
    

    虽然就个人而言,我更愿意使用其他功能方法之一,例如 mapreduce,具体取决于您要执行的操作。

    注意:我写的是 Underscore.cfc

    【讨论】:

      【解决方案3】:

      你可以使用:

      <cfscript>
          for (key in struct) {
              writeOutput("#key# = #struct[key]# <br>");
          }
      </cfscript>
      

      <cfoutput>
          <cfloop collection="#params#" item="key" >
              #key# = #params[key]#         
          </cfloop>
      </cfoutput>
      

      记得在 Applicacion.cfc 中设置“this.serialization.preservecaseforstructkey = true”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 2012-12-25
        相关资源
        最近更新 更多