这怎么可能是输出?

时间:2018-05-27 08:51:55

标签: actionscript-3 flash flash-builder

这是简单的程序,但程序的输出是如此出乎意料。

编程语言:ActionScript 3.0 enter image description here

1 个答案:

答案 0 :(得分:2)

所以,我们有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变量声明是 NOT 操作。它是一种结构,告诉编译器您将在给定的上下文中使用具有特定名称和类型的变量(作为类成员或作为时间轴变量或作为方法中的局部变量) 。从字面上看,您声明变量的代码无关紧要。我必须承认,从这个角度来看,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);
    }
}