2010-09-17 75 views
2

如果我没有在我的代码中专门输入一个变量,它会编译为默认数据类型?例如,“每个...在”功能的效果最好,而无需输入变量:ActionScript - 非类型变量的默认数据类型?

for each (var element in myArray) 
     { 
     //process each element 
     } 

做我元素变量有数据类型?如果输入Object为实际编写元素:Object或者它有什么关系?

编辑

实际上,这是一个坏榜样,因为元素变量将被输入到任何元素是myArray的。

但它是如何工作的,如果一个变量是无类型的?它会变成什么传递给它?

这里是我的问题一个更好的例子:

var a = "i'm a string"; //does this var becomes a String? 

var b = 50.98; //does this var becomes a Number? 

var c = 2; //does this var becomes an int? 
+0

看到我更新... – Amarghosh 2010-09-17 12:56:32

回答

3

for each (var element in myArray)

element变量不具有任何数据类型 - 它是类型化的,因​​此可以容纳任何东西。

是的,它相当于编写element:Objectelement:*,但总是建议您键入变量 - 这将帮助您在运行代码之前捕获一些错误。如果不这样做,mxmlc编译器将发出警告,可通过将其键入e:Objecte:*来修复该警告。


var a = 45.3; //untyped variable `a` 
a = "asd";  //can hold anything 

/* 
    This is fine: currently variable `a` contains 
    a String object, which does have a `charAt` function. 
*/ 
trace(a.charAt(1)); 

a = 23; 
/* 
    Run time error: currently variable `a` contains 
    a Number, which doesn't have a `charAt` function. 
    If you had specified the type of variable `a` when 
    you declared it, this would have been 
    detected at the time of compilation itself. 
*/ 
trace(a.charAt(1)); //run time error 


var b:Number = 45.3; 
b = "asd"; //compiler error 
trace(a.charAt(1)); //compiler error 
+0

奇怪。好的,我会输入它们,即使我使用的是Flash Professional,而不是Flash Builder,但它不会给出警告,但我认为这是很好的做我会迁移到该编译器。另外,actionscript文档不会在for循环中键入var:http://bit.ly/a2tZc9 – TheDarkIn1978 2010-09-17 12:38:22

+0

始终键入。不仅要抓住错误,还要抓住性能。 Flash就是这样,寻找每一种可能的优化都是不错的主意,特别是像这样简单的优化。 – Raveline 2010-09-17 13:10:45

+0

总是输入你的变量,吃你的蔬菜! – grapefrukt 2010-09-17 16:12:16