Pick random Element of an Array Actionscript 3

坚强是说给别人听的谎言 提交于 2019-12-30 06:29:53

问题


I have an array of movieclips and i want to put them on stage. so they have to be unique and randomly chosen.

how can I do that?

thank you for your time


回答1:


You can get a random number using Math.random() This will return a number between 0 and 1.

So, for getting a random element of the array, use this:

function getRandomElementOf(array:Array):Object {
    var idx:int=Math.floor(Math.random() * array.length);
    return array[idx];
}



回答2:


If you have an Array already, you should be able to define a random sort, then you can add them to the stage as needed.

//get your array as needed...
var myArray:Array = getYourMovieClipsArray();

//randomize it by "sorting" it...
myArray.sort(randomSort);

//do something with them...
for(var i:int=0;i<myArray.length;i++){
    addChild(myArray[i]);
}



//sorting function
public function randomSort(objA:Object, objB:Object):int{
    return Math.round(Math.random() * 2) - 1;
}


来源:https://stackoverflow.com/questions/7913412/pick-random-element-of-an-array-actionscript-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!