VUE随机洗牌,JS随机排序数组/洗牌函数
第一步:新建一个名为tools.js的文件
//随机排序数组/洗牌函数
function copyArray(source, array) {
let index = -1;
const length = source.length;
array || (array = new Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
export const randomSortArray = function shuffle(array) {
const length = array == null ? 0 : array.length;
if (!length) {
return [];
}
let index = -1;
const lastIndex = length - 1;
const result = copyArray(array);
while (++index < length) {
const rand = index + Math.floor(Math.random() * (lastIndex - index + 1));
const value = result[rand];
result[rand] = result[index];
result[index] = value;
}
return result;
}
第二步:在页面中引入随机洗牌函数,并使用
// 在页面中引入随机洗牌函数
import { randomSortArray } from "@/utils/tools.js";
// 在方法中使用
let arr = [];
for (let i = 0; i < 52; i++) {
arr.push(i + 1);
}
console.log(arr);
let newArr = randomSortArray(arr);
console.log(newArr);
// 打印结果1:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
// 打印结果2:[41, 35, 47, 44, 38, 21, 10, 51, 49, 13, 20, 11, 43, 40, 52, 24, 9, 8, 29, 25, 27, 19, 36, 31, 39, 45, 23, 42, 14, 17, 18, 30, 4, 48, 16, 33, 34, 32, 1, 5, 28, 37, 3, 50, 15, 26, 46, 6, 12, 2, 7, 22]