在 javascript 裡要去讓一個陣列的內容可以隨機排列,只要透過 sort 跟 random 的方法就可以了。

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

 

定義完這個 function 後,就可以直接使用了:

console.log(shuffleArray([1, 2, 3, 4]));