从数组中选择随机元素,而无需重复 [英] Pick random elements from an array without repeating
本文介绍了从数组中选择随机元素,而无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要在单个子画面上显示随机数,并希望对单个容器进行洗牌,使其上没有显示相同的内容.如何在不重复相同颜色的情况下随机随机播放一组精灵?
I'm displaying random numbers on individual sprites and want to shuffle the individual container with the same no displaying on it. how to shuffle a set of sprites randomly without repeating the same color?
我的数组是:
var color = new Array();
color[0] = 'greenBox';
color[1] = 'blueBox';
color[2] = 'purpleBox';
color[3] = 'yellowBox';
color[4] = 'redBox';
color[5] = 'whiteBox';
color[6] = 'pinkBox';
推荐答案
如果以后不再需要该数组,则可以执行以下操作:
If you don't need the array later, you could do something like this:
var color = [
"greenBox",
"blueBox",
...
];
while (color.length != 0) {
var index = Math.floor(Math.random()*color.length);
var pickedColor = color[index];
colors.splice(index, 1); // This removes the picked element from the array
doStuffWith(pickedColor);
}
这会破坏数组,但永远不会两次选择相同的元素
This will destroy the array, but it will never pick the same element twice
这篇关于从数组中选择随机元素,而无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文