繁体   English   中英

从字符串数组中获取多个随机字符串

[英]Getting multiple random strings from array of strings

如何从字符串数组中获取多个随机字符串。 例如:

const arr = [
'Text1',
'Text2',
'Text3',
'Text4',
'Text5'
]

结果:

const randomStrings = [
'Text1',
'Text4'
]

您可以使用Math.random() 这将生成一个介于 0 和 1(不包括 1)之间的随机数。 然后,您可以将此数字乘以数组的长度,并使用Math.floor()在数组中生成索引。 当我们使用splice ,它会改变原始数组,但它确保不会有重复的值。

 const arr = ['Text1', 'Text2', 'Text3', 'Text4', 'Text5'] const out = [] const elements = 2 for (let i = 0; i < elements; i++) { out.push(...arr.splice(Math.floor(Math.random() * arr.length), 1)) } console.log(out)

正如 Terry 所提到的,最好创建一个数组的本地副本,这样它就不会被修改。 它还允许传递参数来选择返回的元素数量:

 const arr = ['Text1', 'Text2', 'Text3', 'Text4', 'Text5'] const getRandomElements = (a, n) => { const l = a.slice() const o = [] for (let i = 0; i < n; i++) { o.push(...l.splice(Math.floor(Math.random() * l.length), 1)) } return o } console.log(getRandomElements(arr, 2)) console.log(getRandomElements(arr, 3)) console.log(getRandomElements(arr, 4))

暂无
暂无

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

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