Pick random elements from an array without repeating

放肆的年华 提交于 2019-12-02 10:24:35

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

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