高级前端
js
【Q495】如何把一个数组随机打乱

如何把一个数组随机打乱

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 504 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

使用原生实现,Math.rondom() - 0.5 有时大于0,有时小于0会达成这样的效果

[1, 2, 3, 4].sort((x, y) => Math.random() - 0.5);

借用 lodash 可更方便

_.shuffle([1, 2, 3, 4]);
//-> [3, 2, 4, 1]