ActionScript - 无类型变量的默认数据类型?

时间:2010-09-17 12:19:39

标签: actionscript-3 types default

如果我没有在我的代码中专门输入变量,它会编译为默认数据类型吗?例如,“for each ... in”函数在不键入变量的情况下效果最佳:

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

我的元素变量是否具有数据类型?如果它被输入为Object,那么实际编写 element: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?

1 个答案:

答案 0 :(得分: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
相关问题