Actually, it's both a very useful technique, and only a problem if you're
using CFLOOP.  Say you want to remove duplicate elements from a list.  If
you remove anything, you'll just get an "invalid list index" error, but if
you use CFSCRIPT you'll be just fine.

Here's code for the two different methods.  The script call returns
"1,2,3,4,5", just as it's supposed to, but the tag call throws an "Invalid
list index 6." error.

<cfscript>
function dedupeListScript(list) {
var map = structNew();
var i = "";
for (i = 1; i LT listLen(list); i = i + 1) {
if (structKeyExists(map, listGetAt(list, i))) {
list = listDeleteAt(list, i);
i = i - 1;
} else {
map[listGetAt(list, i)] = "";
}
}
return list;
}
</cfscript>

<cffunction name="dedupeListTag">
<cfargument name="list" />
<cfset var map = structNew() />
<cfset var i = "" />
<cfloop from="1" to="#listLen(list)#" index="i">
<cfif structKeyExists(map, listGetAt(list, i))>
<cfset list = listDeleteAt(list, i) />
<cfset i = i - 1 />
<cfelse>
<cfset map[listGetAt(list, i)] = "" />
</cfif>
</cfloop>
<cfreturn list />
</cffunction>

<cfset myList = "1,1,2,3,4,4,5" />
<cfoutput>#dedupeListScript(myList)#</cfoutput>
<cfoutput>#dedupeListTag(myList)#</cfoutput>

> -----Original Message-----
> From: Philip Arnold [mailto:[EMAIL PROTECTED]
> Sent: Friday, April 16, 2004 11:05 AM
> To: CF-Talk
> Subject: RE: cfloop
>
> > From: Barney Boisvert
> >
> > <cfset a = arrayNew(1) />
> > <cfset arraySet(a, 1, 10, 42) />
> > <cfloop from="1" to="#arrayLen(a)#" index="i" step="1">
> > <cfset arrayDeleteAt(a, 1) />
> > </cfloop>
> > <cfoutput>#i#-#arrayLen(a)#</cfoutput>
>
> But why would you do this in the first place?
>
> Looping over an array that you're changing the size of within the loop
> is just asking for trouble
>
>
>
>
[Todays Threads] [This Message] [Subscription] [Fast Unsubscribe] [User Settings]

Reply via email to