为什么这个“绑定”不是代码在JavaFX中按预期工作? [英] Why doesn't this "binding" code work as expected in JavaFX?

查看:121
本文介绍了为什么这个“绑定”不是代码在JavaFX中按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaFX的新手。我无法理解为什么下面的代码不起作用。

I am new to JavaFX. I am not able to understand why the code below doesn't work.

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

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

Clearly, the counter increment in the loop is not treated as a value change and the bound expression is not re evaluated.

任何人都可以解释这种行为背后的概念吗?

Can anyone please explain the concept behind this behavior?

推荐答案

for 表达式隐式定义了它的迭代变量(这就是你不需要在第二个例子中声明 i 的原因)。即使已经存在具有相同名称的变量, for 仍将为其范围创建一个新变量。您的 bind 表达式绑定到 for 循环之外的 curr 变量,而不是 for 中的 curr 变量环。并且循环外部的那个不会改变,因此绑定的表达式不会改变。

The for expression implicitly defines its iteration variable (that's why you didn't need to declare i in your second example). Even if there is already a variable with the same name, for will still create a new one for its scope. Your bind expression is bound to the curr variable outside of your for loop, not to the one inside your for loop. And the one outside of your loop doesn't change, so the bound expression will not change.

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

Example to demonstrate this behaviour of 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 循环外的 curr 将不会改变 for 循环中的同名变量。

Thus the curr outside the for loop won't change if you modify a variable of the same name inside the for loop.

这篇关于为什么这个“绑定”不是代码在JavaFX中按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆