下面的代码适用于普通数组,但不适用于带有对象的数组。有人知道该怎么做吗?
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
const result = shuffle(array);
console.log(JSON.stringify(result));
最佳答案
尝试像这样的片段排序:
console.log( [
{ some: 1 },
{ some: 2 },
{ some: 3 },
{ some: 4 },
{ some: 5 },
{ some: 6 },
{ some: 7 },
]
.sort( () => Math.random() - 0.5) );
作为对 Martin Omanders 评论的回应:这里是根据 Fisher-Yates algorithm 的随机播放方法。
const result = document.querySelector("pre");
for (let i=0; i<20; i+=1) {
result.textContent +=
JSON.stringify(shuffleFisherYates([0,1,2,3,4,5,6,7,8,9])) + '\n';
}
function shuffleFisherYates(array) {
let i = array.length;
while (i--) {
const ri = Math.floor(Math.random() * i);
[array[i], array[ri]] = [array[ri], array[i]];
}
return array;
}
<pre></pre>
可以浓缩为一个衬里( 注释 :这个衬里不会在 Google Closure Compiler 高级级别中编译):
const shuffle = array =>
[...Array(array.length)]
.map((el, i) => Math.floor(Math.random() * i))
.reduce( (a, rv, i) => ([a[i], a[rv]] = [a[rv], a[i]]) && a, array);
const result = document.querySelector("pre");
for (let i=0; i<100; i+=1)
result.textContent +=
JSON.stringify(shuffle([0,1,2,3,4,5,6,7,8,9])) + '\n';
<pre></pre>
关于javascript - 如何在javascript中打乱一组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49555273/