Skip to content

Function: randomChoice()

ts
function randomChoice<T>(array): T;

Picks a random element from an array. 从数组中随机选择一个元素。

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
arrayT[]The array to pick from / 要选择的数组

Returns

T

A random element from the array / 数组中的随机元素

Throws

Error if array is empty / 如果数组为空则抛出错误

Example

typescript
randomChoice([1, 2, 3, 4, 5]) // => one of the numbers
randomChoice(['apple', 'banana', 'orange']) // => one of the fruits

Since

1.0.0

Released under the MIT License.