另一种选择是使用map 和/或reduce 闭包函数来解析您的列表。
注意 1:我通常发现 cfscript 对于解析文本或“循环”的大多数事情要容易得多。
注意 2:我不是循环的忠实粉丝,尤其是在大文本值周围。闭包函数的性能可能会更高。
<cfset lst ="group 1:1; group 2:4; group a:7; group 1:3; group a:1;">
首先,在函数内部使用map():
<cfscript>
public Struct function parseLst (required String lst) {
var retval = {} ; //// Default return variable.
//// https://docs.lucee.org/reference/functions/listmap.html
arguments.lst.listmap(
function(el) {
var k = el.listFirst(":").ltrim() ; /// Get the "key" and strip extra leading space.
var v = el.listLast(":") ; /// Get the "value".
var p = retval["#k#"]?:0 ; /// Use Elvis to default to 0 if no struct Key exists.
retval["#k#"] = v + p ; /// Set the value of the key. NOTE: A struck key with the same name will generally overwrite itself. We want to add it.
}
,";" /// Specify the delimiter of the list.
) ;
return retval ;
}
writeDump(parseLst(lst));
</cfscript>
然后使用reduce() 而不在函数内部。
<cfscript>
//// https://docs.lucee.org/reference/functions/listreduce.html
r = listReduce(lst,
function(prev,nxt){
k = nxt.listFirst(":").ltrim() ; /// Get the "key" and strip extra leading space.
/// To shorten it, I just skipped setting the value beforehand and just did it while setting the struct value. Same method as above.
prev["#k#"] = (nxt.listLast(":"))+(prev["#k#"]?:0) ;
return prev ;
}
,
{} // Initial value
,";" // Delimiter
) ;
writedump(r) ;
</cfscript>
两者都可以(并且可能应该)在一个函数中,然后您可以将您的列表变量发送给它。
如果可能的话,修复原始列表以使其更易于使用可能会容易得多。
https://trycf.com/gist/dda51d88504a625fce5548142d73edb3/lucee5?theme=monokai
================================================ ========
编辑:
使用listFirst/Last() 函数的替代方法是将“列表”转换为数组,然后使用这些部分来获取“键”和“值”。
<cfscript>
//// https://docs.lucee.org/reference/functions/listreduce.html
s = listReduce(lst,
function(prev,nxt){
var elem = nxt.listToArray(":") ;
prev["#elem[1].ltrim()#"] = elem[2] + (prev["#elem[1].ltrim()#"]?:0) ;
return prev ;
}
,
{} // Initial value
,";" // Delimiter
) ;
writedump(s) ;
</cfscript>