对于循环变量的作用域混乱 [英] For-loop variable scope confusion

查看:246
本文介绍了对于循环变量的作用域混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到一个奇怪的行为变量的for循环。这不是一个真正的问题,但它扰乱了我很多。
其实我已经创建了两个循环是这样的:

I have noticed a weird behavior of the variables in for loops. It's not really a problem, but it disturbs me a lot.
Actually I've created two loops this way:

for (var i:uint; i<19; i++) SomeFunction (i);
for (var i:uint; i<26; i++) SomeOtherFunction (i);

我收到了一个编译警告:
警告:重复的变量定义

What I received was a compilation warning:
Warning: Duplicate variable definition.

此警告真是出乎我的意料。没有像以往任何时候都发生在我身上的其他语言。
看来,变量进入那就是在更高的层次和可用圈外的块的范围。我也试着去拥抱循环块的大括号,但它并没有改变任何东西。
它为什么会发生?它是正常的吗?是否有可能避免呢?现在我只是设置不同的名称,这两个变量的,但是这不是一个真正的解决办法,我认为。我真的很想使用 -named变量在大多数我的for循环的。

This warning really surprised me. Nothing like that ever happened to me in other languages.
It seems that the i variable gets into the scope that is higher in the hierarchy and becomes available out of the loop's block. I've also tried to embrace the loop block in a curly brace, but it didn't change anything.
Why does it happen? Is it normal? Is it possible to avoid it? For now I've just set different names for both of the variables, but that's not a real solution I think. I'd really like to use the i-named variable in most of my for-loops.

推荐答案

是的,循环增量变量在循环父的范围,循环本身不进去。这是故意的,像这样的例子:

yes, the loop increment variable is in the scope of the loops parent, not inside the loop itself. This is intentional, for examples like this:

public function getPositionOfValue ( value:String ) : int
{
    for ( var i:int = 0; i < someArray; i++ )
    {
        if (someArray[i] == value )
        {
            break;
        }
    }

    return i;
}

这允许你访问i的值,一旦循环结束。有很多情况下,这是非常有用的。

this allows you to access the value of i once the loop is over. There are lots of cases where this is very useful.

你应该做在你有多个循环的情况下,内部的相同的范围是VAR环路外的我:

What you should do in the cases where you have multiple loops inside the same scope is var the i outside of the loops:

public function getPositionOfValue ( value:String ) : int
{
    var i:int;

    for ( i = 0; i < 15; i++ )
    {
        //do something
    }

    for ( i = 0; i < 29; i++ )
    {
        //do something else
    }

    return i;
}

然后你摆脱你的警告。另外要考虑的是你的名字循环增量变量更具描述性。

then you get rid of your warning. The other thing to consider is to name your loop increment variables something more descriptive.

更新:两个其他的事情要考虑:

Update: Two other things to consider:

1),则不应使用uints除了像的颜色和地方的Flex需要一个UINT。他们是慢于廉政局使用。来源] 1 更新:它看起来像这样可以不再在新版本的Flash播放器的情况下:

2)当你VAR循环递增变量的循环声明里面,你要确保你将它设置为正确的初始值,通常为0。你可以得到一些硬的,如果你不追查错误。

2) when you var a loop increment variable inside of a loop declaration, you want to make sure you set it to the proper initialization value, usually 0. You can get some hard to track down bugs if you dont.

这篇关于对于循环变量的作用域混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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