我是JavaFX的新手.我无法理解为什么下面的代码不起作用.
import javafx.util.Sequences; def nums = [1..10]; var curr = 0; var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number"; for (curr in [0..(sizeof nums -1)]) { println("{evenOrOdd}"); }
我正进入(状态
1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number 1 is an odd number
如果我将代码更改为
import javafx.util.Sequences; def nums = [1..10]; var curr = 0; var evenOrOdd = bind if (nums[curr] mod 2 == 0) "{nums[curr]} is an even number" else "{nums[curr]} is an odd number"; for (i in [0..(sizeof nums -1)]) { curr = i; println("{evenOrOdd}"); }
我得到了正确的输出:
1 is an odd number 2 is an even number 3 is an odd number 4 is an even number 5 is an odd number 6 is an even number 7 is an odd number 8 is an even number 9 is an odd number 10 is an even number
显然,循环中的计数器增量不会被视为值更改,并且不会重新计算绑定表达式.
任何人都可以解释这种行为背后的概念吗?
将用于表达含蓄地定义了它的迭代变量(这就是为什么你没有需要声明我在你的第二个例子).即使已经存在具有相同名称的变量,for仍将为其范围创建一个新变量.您绑定表达式绑定到CURR变量之外你的循环,而不是你的内部一个用于循环.循环外部的那个不会改变,因此绑定的表达式不会改变.
例子来说明这种行为的:
var curr = 0; var ousideCurrRef = bind curr; println("Before 'for' loop: curr={curr}"); for (curr in [0..3]) { println("In 'for' loop: curr={curr} ousideCurrRef={ousideCurrRef}"); } println("After 'for' loop: curr={curr}");
这将打印:
Before 'for' loop: curr=0 In 'for' loop: curr=0 ousideCurrRef=0 In 'for' loop: curr=1 ousideCurrRef=0 In 'for' loop: curr=2 ousideCurrRef=0 In 'for' loop: curr=3 ousideCurrRef=0 After 'for' loop: curr=0
因此,CURR外的,如果你修改了相同名称的变量里面的循环不会改变的循环.