【发布时间】:2020-03-12 22:51:00
【问题描述】:
我想在 javascript 中打乱一个数组...
我先写了这个函数:
function shuffle(arr) {
for (i = 0; i < arr.length; i++) {
let temp0 = arr[Math.floor(Math.random() * arr.length)];
let temp1 = arr[Math.floor(Math.random() * arr.length)];
console.log(temp0); // select random item work correctly
console.log(temp1); // select random item work correctly
if (temp0 === temp1) { //for dont change arr[index] with save value!!!
continue;
}
temp2 = temp0;
temp0 = temp1;
temp1 = temp2;
console.log(temp0); //all temp0, temp1, temp2 are equal!!!
console.log(temp1); //all temp0, temp1, temp2 are equal!!!
console.log(temp2); //all temp0, temp1, temp2 are equal!!!
}
return arr
}
我的算法如下:
- 随机选择一个项目
- 随机选择另一个项目
- 将两个项目一起切换
但我最终得到 temp0、temp1 和 temp2 都相等!!!
然后我将我的代码更改为这个,它可以完美运行
function shuffle1(arr) {
for (i = 0; i < arr.length; i++) {
x = Math.floor(Math.random() * arr.length);
y = Math.floor(Math.random() * arr.length);
if (x === y) { //for dont change arr[index] with self !!!
continue;
}
temp0 = arr[x];
arr[x] = arr[y];
arr[y] = temp0;
}
return arr
}
唯一发生的变化是:将随机创建的索引编号分配给一个变量,然后该变量用于选择数组中的一项。
谁能帮我理解为什么第一个示例在第二个示例中没有按预期工作?
提前致谢
【问题讨论】:
-
这能回答你的问题吗? How can I shuffle an array?
-
你在
tmep0 = temp1;的shuffle()中有错字,而javascript 引用了外部(全局)范围内的变量
标签: javascript arrays shuffle