【问题标题】:Looping over an array nested within a structure遍历嵌套在结构中的数组
【发布时间】:2018-10-25 18:31:58
【问题描述】:

这是 API 返回的一些数据。我需要遍历嵌套结构中包含的数组。例如下图中的savedMajorIds:

isArray(apiprofile.result.savedMajorIds)

返回 Yes,所以我很确定它正在寻找正确的东西。但是,当我尝试遍历它以获取它破坏的值时。代码是:

for (i=1, i < arrayLen(apiprofile.result.savedMajorIds),i=i+1) {
        writeOutput(apiprofile.result.savedMajorIds[i]);
    }

错误日志不喜欢 arrayLen() 部分,但到目前为止我一直无法让它工作。

【问题讨论】:

  • 什么版本的 ColdFusion?

标签: coldfusion cfml


【解决方案1】:

对于其他偶然发现此问题的人:

(i=1, i < arrayLen(apiprofile.result.savedMajorIds),i=i+1)

需要

(i=1; i < arrayLen(apiprofile.result.savedMajorIds); i=i+1)

(i=1; i < arrayLen(apiprofile.result.savedMajorIds); i++)

【讨论】:

  • (他把逗号,换成了分号;。)
  • 为了以后参考,也可以使用foreach-syntax:for (id in apiprofile.result.savedMajorIds) { }
【解决方案2】:

这里有几个选项,具体取决于您的 ColdFusion 版本。

if (isArray(apiprofile.result.savedMajorIDs)) {
    // For/In Loop on Array - Possibly CF9, Definitely CF10+ (Verify version) 
    // Note: x will leak unless var'ed inside function.
    for ( x IN apiprofile.result.savedMajorIDs ) {
        writeoutput( x & "<br>" ) ;
    }

    // ArrayEach - CF10+ > Note: y will not leak.
    ArrayEach(apiprofile.result.savedMajorIDs, function(y){writeoutput(y & "<br>");}) ;

    // Member Function .each() - CF11+  > Note: z will not leak.
    apiprofile.result.savedMajorIDs.each( function(z){writeoutput(z & "<br>");}) ;
}

https://trycf.com/gist/f6f3e64635e4b72da15521a3d49d485f/acf11?theme=monokai

【讨论】:

  • 用各种方法做一些测试,for/in 循环似乎比其他方法快得多。这适用于列表、数组、结构,尤其是查询。
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2017-05-13
  • 2017-09-08
相关资源
最近更新 更多