5

我是 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

显然,循环中的计数器增量不会被视为值更改,并且不会重新评估绑定表达式。

谁能解释一下这种行为背后的概念?

4

1 回答 1

6

for表达式隐式定义了它的迭代变量(这就是为什么您不需要在第二个示例中声明i的原因)。即使已经有一个同名的变量,for仍然会为其作用域创建一个新变量。您的绑定表达式绑定到for循环外部的curr变量,而不是绑定到for循环内的变量。并且循环之外的那个不会改变,所以绑定的表达式不会改变。

演示for 的这种行为的示例:

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

因此,如果您在for循环内修改同名变量,则for循环外的curr不会改变。

于 2009-03-18T19:21:32.097 回答