切换布尔问题
这段代码是用简单的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在函数
changeBoolean
中,您正在更改boolean
的值(顺便说一下,这个名字很糟糕 - 尽量避免与内置类型的命名冲突,即使是不同的类型)外壳)参数。这在该函数之外没有任何影响。您想要更改
myBool
的值(我将其称为 .Net 或 Java 中的类字段)。...这就是我要做的(同样,对 ActionScript 有着幼稚的理解)。
In the function
changeBoolean
, you're changing the value of theboolean
(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....is what I would do (again, with a naive understanding of ActionScript).
您正在将值传递给函数,而不是引用。这意味着您的changeBoolean函数内的布尔值是从myBool变量复制的,因此当您在函数内更改它时,它并没有真正更改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: