在我的循环中,我有一个不断变化的数字 - 我需要弄清楚如何判断数字是增加还是减少:
一些不起作用的伪代码:)
var now:Number;
var then:Number;
function loop():void
{
now = changingNumber;
then = changingNumber;
if (now > then) {
// increasing
}else {
// decreasing
}
}
答案 0 :(得分:7)
var now:int = 0;
var thn:int = 0;
function loop():void
{
// Change the number.
now = changingNumber;
if(now > thn)
{
trace("Got larger.");
}
else if(now < thn)
{
trace("Got smaller.");
}
else
{
trace("Maintained value.");
}
// Store the changed value for comparison on new loop() call.
// Notice how we do this AFTER 'now' has changed and we've compared it.
thn = now;
}
或者,您可以为您的值准备一个getter和setter,并管理那里的增加或减少。
// Properties.
var _now:int = 0;
var _thn:int = 0;
// Return the value of now.
function get now():int
{
return _now;
}
// Set a new value for now and determine if it's higher or lower.
function set now(value:int):void
{
_now = value;
// Comparison statements here as per above.
// ...
_thn = _now;
}
此方法效率更高,不需要循环。