function shuffleD(arr) { for(let i = 0,len = arr.length; i < len; i++){ let j = parseInt(Math.random() * (len - 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; console.log(arr); } console.log(arr) return arr; }
shuffleD(arr);
--------------------------------其他的写作形式----仅供参考-------------------------------------------------
function shuffleA(arr) { for(let i = arr.length-1;i > -1;i--){ let j = Math.floor(Math.random() * i); [arr[j], arr[i]] = [arr[i], arr[j]]; } console.log(arr) return arr; } function shuffleB(arr) { for(let i = 0,len = arr.length; i < len; i++){ let currentRandom = parseInt(Math.random() * (len - 1)); let current = arr[i]; arr[i] = arr[currentRandom]; arr[currentRandom] = current; console.log(arr); } console.log(arr) return arr; } function shuffleC(arr) { let i = arr.length; while (i) { let j = Math.floor(Math.random() * i--); [arr[j], arr[i]] = [arr[i], arr[j]]; } console.log(arr) return arr; }