找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/core/utility/UtilityMath.ts
1export class UtilityMath {
2
3 /**
4 * 数组洗牌工具方法
5 * @param array 要洗牌的数组
6 * @returns 洗牌后的数组
7 */
8 public static ShuffleArray<T>(array: T[]): T[] {
9 const newArray = [...array];
10 for (let i = newArray.length - 1; i > 0; i--) {
11 const j = Math.floor(Math.random() * (i + 1));
12 [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
13 }
14 return newArray;
15 }
16}
讲解17 行
随机与数学工具人工通读

UtilityMath.ts

目前只提供数组洗牌,用 Fisher-Yates 从后向前随机交换,先复制再打乱,因此返回新数组且不修改入参。抽奖、题目乱序等需要无序结果的逻辑可以直接复用它。

单方法文件,关注它先展开复制、再原地交换副本这一点即可。

特殊处理与易错点

8方法复制数组后用 Fisher-Yates 从末位向前与随机下标交换,返回打乱顺序的新数组。