从数组中删除随机对象

时间:2015-04-22 20:48:55

标签: javascript arrays random

我有一个数组如:

array=['a','b','c','d','e','f'];

我想删除一个随机的2个元素。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

要从数组中获取两个唯一项,如果您不介意改变原始数组,可以使用splice()从数组中删除所选项,以便在运行时不会选中它这是第二次:

var firstRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);
var secondRandomChoice = array.splice(Math.floor(Math.random()*array.length), 1);

如果您使用lodash等实用程序库,则可能已有一个功能可用于执行此操作。例如,lodash提供sample()。因此,如果你使用lodash,你可以做这样的事情来获得两个随机项的数组:

var results = _.sample(array, 2);
相关问题