4.变量值的改变和取回
在我们创建一个变量之后,可以为其赋值;并且只要你愿意,就可以多次为其赋值。如下所示: var firstName; // declare the variable firstName firstName = "Graham"; // set the value of firstName firstName = "Gillian"; // change the value of firstName firstName = "Jessica"; // change firstName again firstName = "James"; // change firstName again var x = 10; // declare x and assign a numeric value x = "loading...please wait..."; // assign x a text value 注意,在上例中我们将变量x的数据类型从数字型改变为字符串型,而这只需要简单地赋给它一个我们想要的数据类型的值。有些编程语言不允许变量的数据类型直接发生变化而ActionScript则允许。
当然,如果以后我们不能取回变量的值那么创建变量并为其赋值就变得毫无意义。要取回变量的值,只要在需要使用变量值的任何地方简单地键入变量名就可以了。无论何时,只要变量名出现(除了在变量声明中以及在赋值语句左边的情况之外),就会被引用为变量的值。这是一些例子: newX = oldX + 5; // set newX to the value of oldX plus 5 ball._x = newX; // set the horizontal position of the ball movie clip to the value of newX trace (firstName); // display the value of firstName in the Output window
注意,在表达式ball._x中,ball是电影剪辑的名字,而._x指明了该电影剪辑的x轴坐标属性(即工作区中的水平位置)。以后,我们将学习更多关于属性的知识。上述例子中的末行 —— trace (firstName); —— 当脚本运行时在Output窗口中显示变量firstName的值,这对于调试你的代码来说是很便利的。
1.检查一个变量是否有值 有时候,在引用某个变量之前我们可能希望核实该变量是否已经被赋值。此前,我们学过,如果一个变量已经被声明但是从未被赋值那么它包含着特定的“非值” —— undefined。为确定某个变量是否已经被赋值,我们可以用关键字undefined与该变量的值相比较。例如: if (someVariable != undefined) { // any code placed here is executed only if someVariable has a value }
请注意不等号运算符(!=)的使用,它判断两个值是否不相等。
出处:蓝色理想
责任编辑:无意
上一页 变量(3)- 变量赋值 下一页 变量(5)- 变量值的类型
◎进入论坛Flash专栏版块参加讨论
|