问题
If I have an array, I can set the keys by doing the following:
var example:Array = new Array();
example[20] = "500,45";
example[324] = "432,23";
If I want to do something with Objects, how would I achieve this?
I tried the following:
var example:Object = [{x:500, y:45}, {x:432, y:23}]; // Works but keys are 0 and 1
var example:Object = [20: {x:500, y:45}, 324: {x:432, y:23}]; // Compile errors
var example:Object = [20]: {x:500, y:45}, [324]: {x:432, y:23}; // Compile errors
var example:Object = [20] {x:500, y:45}, [324] {x:432, y:23}; // Compile errors
Is there a good way to achieve this?
I understand I could do this:
var example:Object = {id20 : {x:500, y:45}, id324: {x:432, y:23} };
But it doesn't suit me.
回答1:
The []
notation has the same meaning of doing a new Array()
so when you are doing:
var example:Object = [{x:500, y:45}, {x:432, y:23}];
you are in fact creating an array with two elements who are object {x:500, y:45}
and {x:432, y:23}
.
If you want to create an object with key 20 and 324 use the {}
notation who is the same a new Object()
So your example became =>
var example:Object = {20: {x:500, y:45}, 324: {x:432, y:23}};
You can do the same as your first example using an Object
instead of an Array
:
var example:Object = new Object();
example[20] = "500,45";
example[324] = "432,23";
来源:https://stackoverflow.com/questions/2071871/setting-actionscript-object-keys