为什么函数内部的运算符'+'不会修改* def制成的变量? [英] Why operator '+' inside functions does not modify * def made variables?
问题描述
我正在尝试处理从API获得的json-s列表.
I'm trying to process a list of json-s that I got as an answer from an API.
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
我必须对字段求和,并且为它想出了一个代码,但是看来它并没有修改mySum变量.
I have to sum the fields and I came up with a code for it, but it seems like it does not modify the mySum variable.
在此示例中,我仅使用了'originalEstimate'.
For this example, I just used the 'originalEstimate'.
我尝试手动添加元素,并且可以正常工作.例如:(parseFloat(getNum(json [0] .originalEstimate)))== 16.0
I tried to add manually the elements and that works. Ex.: (parseFloat(getNum(json[0].originalEstimate))) == 16.0
getNum是一个从字符串中削减'h'的函数.
getNum is a function that cuts the 'h' down from the string.
代码如下:
* def getNum = function (a) {return a.substring(0,a.length()-1)}
* text raw =
"""
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
"""
* json json = raw
* def mySum = 0
* def fn = function(x) {mySum = mySum + (parseFloat(getNum(x.originalEstimate)))}
* eval karate.forEach(json,fn)
* print mySum
我希望看到80.0是原始的估算总和,但我收到了0.而且,它运行得很好,只是不修改mySum
I expected to see 80.0 as originalEstimate sum but I received 0. Also, it runs perfectly, just does not modify the mySum
推荐答案
是的,当您声明一个函数时,变量被锁定到声明该函数时的值.解决方法是使用karate.get()
和karate.set()
:
Yes, when you declare a function, variables are locked to the value at the time the function was declared. The solution is use karate.get()
and karate.set()
:
* def getNum = function(x){ return x.substring(0, x.length() - 1) }
* def sum = 0
* def fun = function(x){ var temp = karate.get('sum') + parseFloat(getNum(x.originalEstimate)); karate.set('sum', temp) }
* def response =
"""
[
{
"originalEstimate": "16h",
"remainingEstimate": "9h",
"timeSpent": "7h"
},
{
"originalEstimate": "64h",
"remainingEstimate": "63h",
"timeSpent": "1h"
}
]
"""
* eval karate.forEach(response, fun)
* print sum
这篇关于为什么函数内部的运算符'+'不会修改* def制成的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!