【问题标题】:How can this be the output?这怎么可能是输出?
【发布时间】:2018-11-06 02:40:45
【问题描述】:

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

编程语言:ActionScript 3.0

【问题讨论】:

  • 因为你在循环中声明 score 并给它一个初始值 0。然后它通过 ++ 直到 1。这就是为什么它在跟踪上总是 1 .
  • True :) @Organis :) 您应该将此作为答案而不是评论。我让你这样做,你在我之前回答了;)
  • 你能看看我的一个答案,告诉我我是对还是错? stackoverflow.com/questions/44304338/… 谢谢。
  • @tatactic 不,你的答案在几个方面是不正确的。首先,stage 不是保留字,它是 DisplayObject 类的类成员(如果你想说的话),只要 GameCore 没有子类化 DisplayObject 应该没有问题。其次,保留字链接被破坏。第三,回答一年前的帖子有什么意义吗? OP 解决这个问题可能已经一年了。此外,另一个答案虽然很短,但几乎很到位,代码似乎很好。很抱歉让您对如此详尽的答案感到沮丧。
  • 谢谢@Organis,所以我会删除这个答案。

标签: actionscript-3 flash flash-builder


【解决方案1】:

所以,我们有 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);
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多