空手道 tfw 中 if 语句的变量范围是什么?

What is the variable scope in if statement in karate tfw?

你能帮我理解if语句中变量的作用域吗?

 * def a = "a"
 * if ( 1 == 1 ) a = "b"
 * print "a--",a

 * def str =
      """
      <tag>#(a)</tag>
      """
 * print "str--",str
output : 
[print] a-- a
[print] str-- <tag>b</tag>

当我使用 karate.set('a',"b") 而不是 a = "b" 时,输出看起来是正确的。

[print] a-- b
[print] str-- <tag>b</tag>

JS 引擎在 1.0 RC 中略有改进,我们现在正专注于此:https://github.com/intuit/karate/wiki/1.0-upgrade-guide

* def a = "a"
* if (true) a = "b"
* print "a:", a
* def str = <tag>#(a)</tag>
* print "str:", str

输出为:

[print] a: b 
[print] str: <tag>b</tag>

因此,作为一般规则,我们希望 JS 和空手道 def 变量无缝共存。旧版本确实有一些差距,其中变量往往是 JS 块的局部变量。你是对的,在需要的地方使用 karate.set() 。例如,这非常有用。您在可重复使用的函数或 configure headers 函数中,并且您想要设置或修改“全局”变量。