虽然您应该使用外部 AS 文件(这是一个很好的做法),但这就是您遇到问题的原因,我将逐行解释
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
//This creates an object called car. Suppose it saves it in memory at "location" 0x12345
var test:Array = new Array();
//This creates an empty array
for (var i:Number=0; i<10; i++) {
test.push(car);
//This adds the object "car" to the array
//Since Object is a reference type, its memory location is actually added to the array
//This means you added 0x12345 to the array (10 times over the loop)
}
//The array now contains
[0x12345, 0x12345, 0x12345, .......];
//So now
test[1]; //returns the object at 0x12345
test[1].carscale=5; //sets the carscale property of the object at 0x12345
由于数组中的所有对象都指向相同的位置,因此获取其中任何一个实际上都会返回相同的对象。这意味着它们都将显示carscale
为 5
对此的解决方案是:
var test:Array = new Array();
for (var i:Number=0; i<10; i++) {
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
test.push(car);
}
一个更好的、真正的面向对象的解决方案是创建一个名为 Car 的类,而不是这样做
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
你用
var car:Car = new Car();
课程将Car.as
是这样的:
public class Car {
public function Car() {
//this is the constructor, initialize the object here
//Suppose the default values of the car are as follows:
carcolor="red";
carscale=5;
carpower=1000;
}
public var carcolor:String;
public var carscale:Number, carpower:Number;
}
事实上,您甚至可以使用另一个根据参数自动设置属性的构造函数:
public function Car(_color:String, _scale:Number, _power:Number) {
carcolor=_color;
carscale=_scale;
carpower=_power;
}
并将其称为
var car:Car=new Car("red", 5, 1000);
事实上,car
beforecarcolor
和carscale
甚至carpower
没有必要,因为当你把它们放在一个名为 的类中时很明显Car
。