我想在舞台上添加一堆汽车,并将它们作为对象存储在数组中。问题是我讨厌使用外部 AS 文件,并希望使其尽可能简单。
我试着做:
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
var test:Array = new Array()
for (var i:Number=0; i<10; i++) {
test.push(car)
}
问题是如果我尝试设置一个对象的值
test[1].carscale = 5
数组中的每个对象都将它们的属性 carscale 设置为 5。
有没有什么办法可以在不使用外部类文件的情况下做到这一点?
最佳答案
虽然您应该使用外部 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
之前 carcolor
, carscale
和 carpower
甚至没有必要,因为当您将它们放在名为 Car
的类中时很明显。 .
关于actionscript-3 - AS3 创建对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057558/