javascript - 如何随机选择 3 个元素并将它们从数组中删除?
问题描述
我需要一个函数来选择数组中的 3 个随机元素,并将它们从数组中删除。
解决方案
只需使用Math.random
and从数组中删除一个随机元素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);
推荐阅读
- java - 检查字符串是否包含不是用 Java 编码的 UTF-8 字符
- tensorflow - Tensorflow 2 Hub:如何获得中间层的输出?
- clojurescript - 他们是否使用 clojurescript 转译器来转译转译器?
- azure-pipelines - Azure 管道将“sa”替换为“***”——我该如何配置?
- c - 如何在C中使用数组地址参数按值函数循环传递
- android - 在 react native 中选择下拉项时显示文本输入字段
- javascript - 如何修复由 .get() 方法调用的 URL 生成的 CORB 错误?
- javascript - 使用 Ajax 从表中删除项目
- python - 是否有在 Python 中增加时间戳的函数
- android - getStableInsetTop() 总是返回 0?