首页 > 解决方案 > 这怎么可能是输出?

问题描述

这是一个简单的程序,但程序的输出却出乎意料。

编程语言:ActionScript 3.0 在此处输入图像描述

标签: actionscript-3flashflash-builder

解决方案


所以,我们有 3 种语法:

// 1. Variable declaration.
var a:int;

// 2. Assign value to variable.
a = 0;

// 3. Declare variable and assign value in one go.
var b:int = 1;

棘手的时刻是在 AS3 中的变量声明不是一个操作。它是一种结构,它告诉编译器您将在给定的上下文中使用具有特定名称和类型的变量(作为类成员或时间线变量或方法内的局部变量)。从字面上看,您在代码中声明变量的位置并不重要。我必须承认,从这个角度来看,AS3 是丑陋的。以下代码可能看起来很奇怪,但在语法上是正确的。让我们阅读并理解它的作用和原因。

// As long as they are declared anywhere,
// you can access these wherever you want.
i = 0;
a = 0;
b = -1;

// The 'for' loop allows a single variable declaration
// within its parentheses. It is not mandatory that
// declared variable is an actual loop iterator.
for (var a:int; i <= 10; i++)
{
    // Will trace lines of 0 0 -1 then 1 1 0 then 2 2 1 and so on.
    trace(a, i, b);

    // You can declare a variable inside the loop, why not?
    // The only thing that actually matters is that you assign
    // the 'a' value to it before you increment the 'a' variable,
    // so the 'b' variable will always be one step behind the 'a'.
    var b:int = a;

    a++;
}

// Variable declaration. You can actually put
// those even after the 'return' statement.
var i:int;

让我再说一遍。您声明变量的位置无关紧要,只是您所做的事实。声明变量不是操作。但是,赋值是。您的代码实际上如下所示:

function bringMe(e:Event):void
{
    // Lets explicitly declare variables so that assigning
    // operations will come out into the open.
    var i:int;
    var score:int;

    for (i = 1; i <= 10; i++)
    {
        // Without the confusing declaration it is
        // obvious now what's going on here.
        score = 0;
        score++;

        // Always outputs 1.
        trace(score);

        // Outputs values from 1 to 10 inclusive, as expected.
        trace(i);
    }
}

推荐阅读