如何从AS3中的对象获取随机元素?

时间:2013-09-17 08:22:05

标签: arrays actionscript-3 object random element

您可以从下面的数组中获取随机元素

var list:Array=[1,2,3,4,5];
var randomElement:int = list[ int(Math.random()*list.length) ] ;

但如何从对象中获取随机元素?

var list:Object={a:0,b:1,c:1};
var randomElement:int = //from the list..how??

由于

3 个答案:

答案 0 :(得分:2)

您可以创建临时数组键,例如:

    var list:Object={a:0,b:1,c:2};
    var keys:Array = [];
    for(var key:String in list)
        keys[keys.length] = key;

    var randomElement:int = list[keys[ int(Math.random()*keys.length) ]];

每次需要对象的随机属性时创建新数组都非常昂贵,但我没有看到其他选项来获取它。

答案 1 :(得分:1)

另一种选择(对于这种特殊情况):

 var list:Object={ a:0,b:1,c:2 };
 var max_i:Number = "c".charCodeAt( 0 );
 var min_i:Number = "a".charCodeAt( 0 );
 var range:Number = max_i - min_i ;
 var rand_i:Number = Math.floor( Math.random() * ( range + 1 ) );

 var prop:String = String.fromCharCode( min_i + rand_i );
 var randomElement:int = list[ prop ];

 trace( prop , randomElement );

答案 2 :(得分:0)

这种做法怎么样?

var list:Object = {a:0,b:1,c:1};
var keyCount:int = 3; //number of keys
var randomElement:String;

var randProb:Number = 1.0 / keyCount;

for (randomElement in list)
{
    if (Math.random() < randProb)
    {
        break;
    }
    else
    {
        randProb += 1.0 / keyCount;
    }
}

trace(list[randomElement]);