方法一
使用lodash 的 sampleSize 方法
- _.sampleSize(collection, [n=1])
- 定義:Gets n random elements at unique keys from collection up to the size of collection.
<html>
<head>
<title>test</title>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
</head>
<body>
<script>
var arr = [0,1,2,3,4,5,6,7,8,9];
var data = _.sampleSize(arr, 2);
console.log(data); // 返回長度為2的隨機陣列。返回的陣列中的元素不保證順序。
</script>
</body>
</html>
複製程式碼