JS-根据原始数组随机创建新数组

时间:2019-03-23 23:01:25

标签: javascript

我想创建一个接受数组的函数,然后返回一个新数组,其中包含来自原始数组内部的随机数量的项。请注意,尽管它需要是原始数组中随机数量的项,但它们仍需要保持相同的顺序。知道怎么做吗?

例如:

const originalArr = ['cat', 'dog', 'rabbit', 'hamster', 'parrot'];

/*
 Use Math.random() somehow so that each time you run a function it returns an array with a random amount of the items above inside it, e.g.

['cat', 'rabbit']
['dog', 'rabbit', 'hamster']
[]
['cat', 'parrot']
etc.
*/

1 个答案:

答案 0 :(得分:0)

这是我的尝试。看起来可以工作,但是看起来不是很好。有没有更好的办法?更具功能性的JS风格吗?

myProject