在 Actionscript 3 Flex 中是否可以对对象进行排序或在对象中具有某种顺序?我有一个这样创建的对象:
private var data:Object = new Object();
然后我继续将一些键和值放入其中:
this.data.someKeyOne = 0;
this.data.someKeyTwo = 1337;
this.data.someKeyThree = 123;
之后我遍历对象:
for (var dataPart:String in this.data) {
trace("Key: " + dataPart = " Value:" + this.data["dataPart"]);
}
但我的问题是数据不会按照我初始化它们的顺序显示。这很令人沮丧,因为它需要按照初始化的顺序显示。
最佳答案
正如@helloflash 在 his answer 中所说的那样about 遍历一个对象,并根据 Adobe's definition of associative array
(这是 Object 类的一个实例):
An associative array, sometimes called a hash or map, uses keys instead of a numeric index to organize stored values. Each key in an associative array is a unique string that is used to access a stored value. An associative array is an instance of the Object class, which means that each key corresponds to a property name. Associative arrays are unordered collections of key and value pairs. Your code should not expect the keys of an associative array to be in a specific order.
你得到的行为是正常的,你不能在你的情况下获得有序的键(使用这样的对象)。
如果你不需要 key ,你可以按照@helloflash在his answer中说的那样做,使用简单的数组或向量。否则,您可以使用对象数组,如下所示:
var obj:Object, i:int, s:String;
var data_array:Array = [
{key: 'someKeyOne', value: 0},
{key: 'someKeyTwo', value: 1337},
{key: 'someKeyThree', value: 123}
]
for(i = 0; i < data_array.length; i++){
obj = data_array[i];
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
for (s in data_array) {
obj = data_array[s];
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
for each (obj in data_array){
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
// all these 3 loops give :
// Key : someKeyOne, Value = 0
// Key : someKeyTwo, Value = 1337
// Key : someKeyThree, Value = 123
或者你可以使用 Object,然后像这样将它排序成一个数组:
var data_object:Object = new Object();
data_object.someKeyOne = {index:0, value: 0};
data_object.someKeyTwo = {index:1, value: 1337};
data_object.someKeyThree = {index:2, value: 123};
var tmp_array:Array = sort_obj(data_object);
for(i = 0; i < tmp_array.length; i++){
obj = tmp_array[i];
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
for (obj in tmp_array) {
obj = tmp_array[obj];
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
for each (obj in tmp_array){
trace('Key : ' + obj.key + ', Value = ' + obj.value);
}
function sort_obj(obj:Object):Array {
var a:Array = [];
for (var key:String in obj) {
a.push({key: key, index: obj[key].index, value: obj[key].value});
}
a.sortOn('index', Array.NUMERIC);
return a;
}
// all these 3 loops give :
// Key : someKeyOne, Value = 0
// Key : someKeyTwo, Value = 1337
// Key : someKeyThree, Value = 123
希望能帮到你。
关于actionscript-3 - AS3 Flex 中的排序对象/ map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668518/