【发布时间】:2020-05-08 03:52:17
【问题描述】:
我正在尝试编写代码以从数组中选择 n 个随机元素。例如:
const originalArray = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const randomSelection = (n) => {
if (n > originalArray.length) {
return originalArray;
} else {
//Some Code to randomly select n elements from orignialArray
}
}
const newArray = randomSelection(2); //Random selection of 2 elements from the above array
实现此目的的代码是什么?我搜索了案例,但想知道是否有更简单、更直接的方法来做到这一点。
有什么建议吗?提前非常感谢!
【问题讨论】:
标签: javascript arrays