gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:24:53 31 4
gpt4 key购买 nike

请看下面的代码块:

<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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com