这怎么可能是输出? [英] How can this be the output?

查看:101
本文介绍了这怎么可能是输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

编程语言:ActionScript 3.0

Programming language : ActionScript 3.0

推荐答案

因此,我们有3种语法:

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;

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

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

这篇关于这怎么可能是输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆