Skip to content

shuffle() function

返回使用 Fisher-Yates 算法随机打乱输入数组元素的新数组。

Signature:

typescript
declare function shuffle<T extends Iterable<unknown> | AsyncIterable<unknown>>(
  iterable: T,
  seed?: number,
): ReturnArrayType<T>;

Example

ts
shuffle([1, 2, 3, 4, 5]); // [3, 1, 5, 2, 4] (random order)
shuffle("hello"); // ["o", "e", "l", "h", "l"] (random order) Only ASCII codes are shuffled in the case of a string.
shuffle([1, 2, 3, 4, 5], 42); // [2, 4, 1, 5, 3] (deterministic with seed 42)

Open Source Code

Released under the Apache-2.0 License.