我正在尝试根据搜索字符串从 coldfusion 中的多维数组中删除一个元素(当位置 1 与我的搜索字符串匹配时的完整数组(。我想出了以下内容,它有效(此处数组中的第二个元素被删除(,但它出错了,因为它弄乱了索引 - 当数组长度为 n-1 时,它会尝试检查第 n 个元素删除后。
<cfset Profiles =
[
["aaa", "xdg", "123", "xyz", "ggg" ],
["bbb", "xwa", "234", "xyz", "fff" ],
["ccc", "xed", "567", "xyz", "eee" ],
["ddd", "xae", "789", "xyz", "hhh" ],
["eee", "xsr", "901", "xyz", "bbb" ],
["fff", "xdg", "902", "xyz", "jjj" ]
]/>
<cfset CheckFor = "bbb" />
<cfset Position = 1 />
<cfloop array="#Profiles#" index="arrayIndex" >
ArrayFind: #arrayFind( arrayIndex, CheckFor )#<br />
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
</cfif>
<cfset Position++ />
</cfloop>
<cfdump var="#DocumentProfiles#" />
更改以下内容:
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
</cfif>
<cfset Position++ />
对此:
<cfif #arrayFind( arrayIndex, CheckFor )# eq 1 >
#arrayDeleteAt( Profiles, Position )#
<cfelse>
<cfset Position++ />
</cfif>
如果您是 ACF10+,而不是显式循环,您可以这样做:
<cfscript>
Profiles = [
["aaa","bbb","asdf"]
, ["bbb","asdf","asdfasfs"]
, ["ccc","dfhgasdfg","bbb"]
, ["bbb","asdfasdf","Aasdfa"]
] ;
checkfor = "bbb" ;
//// FROM HERE ////
arrayEach(
Profiles,
function(obj){
obj[1]==checkfor?arrayDelete(Profiles,obj):'';
}
);
//// TO HERE ////
WriteDump(Profiles);
</cfscript>
编辑:或者更好的是,没有循环。仍然是ACF10+,但也在Lucee工作。
p2 = arrayFilter( Profiles, function(obj){ return obj[1] != checkfor ; } );