Open wingmeng opened 5 years ago
随机打乱一个数组中项目的顺序:
function shuffle(arr) { arr = [...arr]; for (let i = 0, len = arr.length; i < len; i++) { var rdmIndex = i + Math.floor(Math.random() * (len - i)); [arr[i], arr[rdmIndex]] = [arr[rdmIndex], arr[i]]; } return arr; } shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
或者封装到数组原型链上:
Array.prototype.shuffle = function() { arr = [...this]; for (let i = 0, len = arr.length; i < len; i++) { var rdmIndex = i + Math.floor(Math.random() * (len - i)); [arr[i], arr[rdmIndex]] = [arr[rdmIndex], arr[i]]; } return arr; } [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle();
随机打乱一个数组中项目的顺序:
或者封装到数组原型链上: