切换布尔问题

发布于 2024-09-19 10:01:14 字数 466 浏览 4 评论 0原文

这段代码是用简单的 ActionScript 编写的,但我假设我的这个问题会出现在所有具有布尔数据类型的语言中。

我只需单击舞台,以便我的布尔变量反转其值,然后跟踪/打印/记录它的新值。但是,它始终跟踪 true,而不是每次单击鼠标时在 true 和 false 之间切换。

我做错了什么?

var myBool:Boolean;

stage.addEventListener(MouseEvent.CLICK, mouseClickHandler);

function mouseClickHandler(evt:MouseEvent):void
    {
    changeBoolean(myBool);
    }

function changeBoolean(boolean:Boolean):void
    {
    boolean = !boolean;
    trace(boolean);
    }

this code is written in simple ActionScript, but i'm assuming this problem of mine would occur in all languages that have boolean datatypes.

i'm simply clicking the stage so that my boolean variable reverses its value and than traces/prints/logs it's new value. however, it's always tracing true instead of switching between true and false for each mouse click.

what am i doing wrong?

var myBool:Boolean;

stage.addEventListener(MouseEvent.CLICK, mouseClickHandler);

function mouseClickHandler(evt:MouseEvent):void
    {
    changeBoolean(myBool);
    }

function changeBoolean(boolean:Boolean):void
    {
    boolean = !boolean;
    trace(boolean);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

誰ツ都不明白 2024-09-26 10:01:21

在函数 changeBoolean 中,您正在更改 boolean 的值(顺便说一下,这个名字很糟糕 - 尽量避免与内置类型的命名冲突,即使是不同的类型)外壳)参数。这在该函数之外没有任何影响。

您想要更改 myBool 的值(我将其称为 .Net 或 Java 中的类字段)。

function mouseClickHandler(evt:MouseEvent):void
    {
    myBool = !myBool;
    trace(myBool);
    }

...这就是我要做的(同样,对 ActionScript 有着幼稚的理解)。

In the function changeBoolean, you're changing the value of the boolean (poor name, by the way - try to avoid naming collisions with built-in types, even with different casing) parameter. This has no effect outside that function.

You want to change the value of myBool (which I would call a class field in .Net or Java) instead.

function mouseClickHandler(evt:MouseEvent):void
    {
    myBool = !myBool;
    trace(myBool);
    }

...is what I would do (again, with a naive understanding of ActionScript).

追我者格杀勿论 2024-09-26 10:01:20

您正在将值传递给函数,而不是引用。这意味着您的changeBoolean函数内的布尔值是从myBool变量复制的,因此当您在函数内更改它时,它并没有真正更改myBool变量。对此基本上有两种解决方案:

  1. 将函数更改为不接受参数,并在其内部更改 myBool 变量或
  2. 更改函数以使其返回布尔参数,并在调用函数时将 myBool 值设置为函数的结果

You are passing a value to the function, not the reference. This means that boolean value inside your changeBoolean function is copied from myBool variable so when you changed it inside the function, it didn't realy change myBool variable. There are basically two solutions to this:

  1. change the function to not accept parameters and inside it change myBool variable or
  2. change the function so that it returns the boolean parameter and on calling the function, set the myBool valu to the result of the function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文