coldfusion - 在 CFML 中循环一个集合(结构)有什么更好的方法吗?

标签 coldfusion coldfusion-9 cfml

请看下面的代码块:

<cfset index = 0 />
<cfloop collection="#anotherPerson#" item="key" >
    <cfset index = index+1 />
    <cfoutput> 
         #key# : #anotherPerson[key]# 
         <cfif index lt ArrayLen(structKeyArray(anotherPerson))> , </cfif>
    </cfoutput>
</cfloop>

<!--- Result 

   age : 24 , haar : Blondes haar , sex : female , ort : Hanau

---->

现在你能告诉我如何在不设置外部索引并在循环内递增它的情况下获得相同的结果吗?如果你仔细注意到,我不得不再写两个 cfset 标签和一个 cfif 用昂贵的代码标记只是为了避免 逗号 (,) 在集合结束时!

最佳答案

好的,我给你看两个答案。第一个将在 ColdFusion 9 上运行。由于其他人可能会发现此线程并使用 Lucee Server 或更新版本的 Adob​​e ColdFusion,因此我包含了一个使用更高阶函数并在 ACF 2016 上运行的单线器。有很多你在 CF9 上缺少的语法糖(如成员函数)和函数式编程。这些答案使用脚本,因为操作数据不是 View (使用标签/模板的地方)。

设置数据

myStruct = { 'age'=24, 'haar'='Blondes haar', 'sex'='female', 'ort'='Hanau' };

CF9兼容 , 将数据转换为数组并使用分隔符添加逗号
myArray = [];
for( key in myStruct ) {
    arrayAppend( myArray, key & ' : ' & myStruct[ key ] );
}
writeOutput( arrayToList( myArray, ', ' ) );

现代 CFML。 使用结构归约闭包将每个键转换为聚合数组,然后将其转换为列表。
writeOutput( myStruct.reduce( function(r,k,v,s){ return r.append( k & ' : ' & s[ k ] );  }, [] ).toList( ', ' ) );

http://cfdocs.org/structreduce

关于coldfusion - 在 CFML 中循环一个集合(结构)有什么更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368551/

相关文章:

javascript - Coldfusion 9 cflayout 选项卡

sql-server - ColdFusion 中的 jTDS 立即超时

ColdFusion:是否可以从 cfscript for in 循环中获取索引?

frameworks - 工单系统的 ColdFusion 框架

ubuntu - 在哪里上传 .bin 文件以安装 ColdFusion

iis - CF 11.使用 ColdFusion.Ajax.submitForm 时出现 'ColdFusion is not defined' 错误

mysql - 如何删除重复的内容?

javascript - ColdFusion - 查询数据表和 CRUD 操作的方法

java - Coldfusion 任务停止运行,日志中显示 "interrupt task"

coldfusion - 当我从 CF6.1 迁移到 CF8 或 Railo3.1 时,有哪些陷阱在等着我?