使用 ColdFusion 循环数组
我有一个购物车数组,其中有一个变量来告诉我该产品是否是配件,这将是或否。我需要遍历购物车并找出以下信息:
- 购物车是否仅包含配件;做任何事。
- 如果购物车仅为产品;做任何事。
- 购物车是否有产品和配件;做任何事。
我一直在尝试这样做:
<cfloop index="i" from="1" to="#arrayLen(session.mycart)#">
<cfif session.mycart[i].accs EQ "yes">
<cfset accPresent = "yes">
</cfif>
<cfif session.mycart[i].accs EQ "no">
<cfset prodpresent = "yes">
</cfif>
</cfloop>
<cfif accPresent EQ "yes" and prodPresent EQ "no">
<cfset bothPresent EQ "yes">
</cfif>
由于未找到 accPresent,这会失败,我认为这是因为循环一次经过一个,并且一旦找到非配件产品,accs 就不等于 yes。实现我想要做的事情的最佳方法是什么?
I have a shopping cart array, which has a variable to tell me if the product is an accessory or not, this will be either yes or no. I need to loop through the cart and find out the following:
- If the cart contains accessories only; do whatever.
- If the cart is products only; do whatever.
- If the cart has products and accessories; do whatever.
I have been trying this:
<cfloop index="i" from="1" to="#arrayLen(session.mycart)#">
<cfif session.mycart[i].accs EQ "yes">
<cfset accPresent = "yes">
</cfif>
<cfif session.mycart[i].accs EQ "no">
<cfset prodpresent = "yes">
</cfif>
</cfloop>
<cfif accPresent EQ "yes" and prodPresent EQ "no">
<cfset bothPresent EQ "yes">
</cfif>
This falls down as accPresent is not found, this i think is due to the fact the loop goes through one at a time and the accs is not equal to yes once it find a non accessory product. What's the best way to achieve what I'm trying to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这样做
Do this
Jason,
您的第三条语句假设 AccPresent 和 ProdPresent 都存在。您是否先创建了它们并给了它们默认值?试试这个:
当然,这假设默认情况下每个都应设置为“否”。
Jason,
Your 3rd statement assumes that AccPresent and ProdPresent will both exist. Did you create them first and give them default values? Try this:
This assumes of course that each of these should be set to "no" by default.
在 ColdFusion 8 及更高版本中,
可以直接使用数组注意:
i
指的是包含数据的结构,而不是数据的位置< a href="http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_j-l_15.html" rel="nofollow">http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_j-l_15.html
In versions of ColdFusion 8 and higher, a
<cfloop>
can use an array directlyNote: That
i
refers to the struct containing the data, not position of the datahttp://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_j-l_15.html
在 CF 10(或 Railo 4)中,可以使用 cfscript 和 Underscore.cfc 库< /a>:
_.find() 的伟大之处在于,一旦迭代器函数返回 true,它就会停止,因此您不必迭代数组中的每个元素。
注意:建议在访问共享范围变量时使用 duplcate() 以防止死锁。
(免责声明:我写了Underscore.cfc)
In CF 10 (or Railo 4), this can be done more elegantly using cfscript and the Underscore.cfc library:
The great thing about _.find() is that it stops as soon as the iterator function returns true, so you don't have to iterate over every single element in the array.
Note: Using duplcate() is recommended when accessing shared-scope variables in order to prevent deadlocks.
(Disclaimer: I wrote Underscore.cfc)