首页 > 解决方案 > 如何随机选择 3 个元素并将它们从数组中删除?

问题描述

我需要一个函数来选择数组中的 3 个随机元素,并将它们从数组中删除。

标签: javascriptarraysrandom

解决方案


只需使用Math.randomand从数组中删除一个随机元素splice,然后执行 3 次:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

arr.splice(Math.floor(Math.random() * arr.length), 1);
arr.splice(Math.floor(Math.random() * arr.length), 1);
arr.splice(Math.floor(Math.random() * arr.length), 1);

console.log(arr);


推荐阅读