gpt4 book ai didi

actionscript-3 - 在循环之外定义变量更好吗?

转载 作者:行者123 更新时间:2023-12-04 16:55:14 25 4
gpt4 key购买 nike

第二个比第一个好?

第一个:

var count:int=myArray.length;
for(var i:uint=0;i<count;i++)
{
var str:String=myArray[i].label;
var somethingElse:Class=...;
var andAnotherThing:MyInstance=new MyInstance(somethingElse);
...
}

第二:
var count:int=myArray.length;
var str:String;
var somethingElse:Class;
var andAnotherThing:MyInstance;
for(var i:uint=0;i<count;i++)
{
str=myArray[i].label;
somethingElse=...;
andAnotherThing=new MyInstance(somethingElse);
...
}

谢谢你。

最佳答案

在 Actionscript 和 Javascript 中,变量的作用域是函数,而不是块。这称为变量提升。

ActionScript 3.0 Variables

An interesting implication of the lack of block-level scope is that you can read or write to a variable before it is declared, as long as it is declared before the function ends. This is because of a technique called hoisting , which means that the compiler moves all variable declarations to the top of the function.



无论您在函数中的何处声明变量,您的代码都会如此有效地表现如下:
var count:int;
var str:String;
var i:uint;
var somethingElse:Class;
var andAnotherThing:MyInstance;

count = myArray.length;
for(i=0;i<count;i++)
{
str=myArray[i].label;
somethingElse = ...;
andAnotherThing = new MyInstance(somethingElse);
...
}

尽管如此,我仍然更喜欢在使用它们的块中声明我的变量,主要是出于维护原因和一般性的清晰度。

关于actionscript-3 - 在循环之外定义变量更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8249903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com