You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ColdFusion中struct结构体字段数值累加运算不生效问题求助

代码存在的问题及修正方案

问题点

  • 变量名大小写不一致:前面定义的变量为thisrecipe(全小写),后续调用getYield()方法时错误使用了大写首字母的thisRecipe,ColdFusion部分运行环境会将两者识别为不同变量,若当前作用域不存在thisRecipe变量会复用前次循环的残留值,导致recipeRatio计算错误,最终thisQuantity取值异常,看起来就像累加操作不生效。
  • recipeRatio未做全场景初始化:该变量的赋值逻辑仅放在thisRecipeYield neq 0的判断分支内,当遇到配方产出为0的场景时,recipeRatio不会被重新赋值,会沿用旧值导致thisQuantity计算错误。
  • 测试输出逻辑顺序错误:你先执行了totalToGet的更新操作,再输出计算过程,此时打印的outerstruct[theitem.getid()].totalToGet已经是更新后的值,自然会出现“新值加新值”的错误展示,让你误以为累加未生效。
  • 结构体键存在类型不匹配隐患:structKeyExists(outerstruct, '#theitem.getid()#')中将id强制转成字符串作为结构体键,若id本身为数字类型,后续用数字取值时会出现找不到键的问题。

修正后的代码

<cfloop list="#recipeItemList#" index="ril">
    <cfset thisRecipe = entityLoadByPK("recipes", ril)>
    <cfloop array="#thisRecipe.getrecipeitem()#" index="recipeItems">
        <cfif recipeItems.hasrawMaterial_id()>
            <cfset theItem = entityLoadByPK("rawMaterials", recipeItems.getrawMaterial_id().getid())>
            <cfinvoke method="getPrepByDate" component="/FEcomponents.production" returnvariable="makeAmount">
                <cfinvokeargument name="recipe_id" value="#ril#">
                <cfinvokeargument name="delivery_date" value="#delivery_date#">
            </cfinvoke>
            <cfset thisRecipeYield = thisRecipe.getYield()>
            <!-- 提前初始化默认值,避免变量未定义 -->
            <cfset recipeRatio = 0>
            <cfif thisRecipeYield neq 0>
                <cfset recipeRatio = makeAmount / thisRecipeYield>
            </cfif>
            <cfset thisQuantity = recipeRatio * recipeItems.getitemQuantity()>
            <!-- 去掉多余的#和引号,直接使用id原值判断 -->
            <cfif structKeyExists(outerstruct, theItem.getid())>
                <!-- 测试输出放在更新操作之前,展示正确的计算过程 -->
                <cfoutput>#outerstruct[theItem.getid()].totalToGet# + #thisQuantity# = #(outerstruct[theItem.getid()].totalToGet + thisQuantity)# <BR></cfoutput>
                <!-- 直接累加赋值,无需调用structInsert -->
                <cfset outerstruct[theItem.getid()].totalToGet += thisQuantity>
            <cfelse>
                <cfset outerstruct[theItem.getid()] = structNew()>
                <cfset outerstruct[theItem.getid()].rawMaterialid = theItem.getid()>
                <cfset outerstruct[theItem.getid()].rawMaterialName = theItem.getName()>
                <cfset outerstruct[theItem.getid()].totalToGet = thisQuantity>
                <cfset outerstruct[theItem.getid()].uom = theItem.getUOM().getname()>
            </cfif>
        </cfif>
    </cfloop>
</cfloop>

内容的提问来源于stack exchange,提问作者Robert Santen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 00:54:00