简体   繁体   English

如何从数组中选择随机元素并将其从列表中删除

[英]How to select Random Element From an Array and Remove it from the List

Can you please let me know how I can select a number randomly from a list and also remove it from the array for the next time?您能否让我知道如何从列表中随机选择一个数字,并在下次将其从数组中删除? For example I have an array as:例如我有一个数组:

var items   = new Array( 2,3,4,5,6,7,8,9,10 );

now I would like to pick one item when a Pick button pushed and add the picked value to a div and also remove the picked item from the array so in next Pick button push it wont be there until to select all of items.现在我想在按下选择按钮时选择一个项目并将选择的值添加到 div 并从数组中删除选择的项目,因此在下一个选择按钮按下它不会在那里,直到选择所有项目。

Thanks for your time谢谢你的时间

Array.splice()

 var items = ["a","b","c","d"]; var randomIndex = Math.floor(Math.random() * items.length); var randomItem = items.splice(randomIndex, 1)[0]; console.log("random item: %o", randomItem); console.log("remaining items: %o", items);

If shuffling the array doesn't matter :如果改组数组无关紧要:

items.sort(function() { return 0.5 - Math.random();}).pop();

FIDDLE小提琴

EDIT:编辑:

I should probably have been a little clearer as the fiddle doesn't really take advantage of the shuffling.我可能应该更清楚一点,因为小提琴并没有真正利用洗牌。
The array only needs to be shuffled once to make it random, after that there is no reason to shuffle it again, just pop of the last value:数组只需要打乱一次使其随机,之后就没有理由再次打乱它,只需弹出最后一个值:

var items   = new Array( 2,3,4,5,6,7,8,9,10 );

items.sort(function() { return 0.5 - Math.random();})

$('#test').on('click', function() {
    var ran = items.pop();
    alert(ran ? ran : 'No more numbers in array');
});

JSPERF JSPERF
JSFIDDLE JSFIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM