0

您可以从如下所示的数组中获取随机元素

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??

谢谢

4

3 回答 3

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) ]];

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

于 2013-09-17T08:27:10.997 回答
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 );
于 2013-09-17T08:39:03.247 回答
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]);
于 2016-02-08T15:13:35.973 回答