Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

actionscript 3 - How can this be the output?

It is simple program, but the output of the program is so unexpected .

Programming language : ActionScript 3.0 enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So, we have 3 kinds of syntax:

// 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;

The tricky moment is that in AS3 variable declaration is NOT an operation. It is a construction that tells compiler you are going to use a variable with a certain name and type within a given context (as a class member or as a timeline variable or as a local variable inside a method). It literally does not matter where in the code you declare your variables. AS3 is, I must admit, ugly from this very perspective. The following code might look weird yet it is syntactically correct. Lets read and understand what it does and why.

// 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;

Let me say it again. The place where you declare your variables does not matter, just the fact you do at all. Declaring variable is not an operation. However, assigning a value is. Your code actually goes as following:

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...