【发布时间】:2020-01-19 13:01:20
【问题描述】:
我正在尝试根据Awais Mirza 的教程修改这个测验应用程序
我想从主数组中随机选择一组问题并将其推送到脚本用于填充问题的选择数组中,因此每次测验都会从主数组中随机给出一组问题正在运行。 我想我可以在将选定数量的问题推入选择数组之前使用 Fisher-Yates shuffle 随机化主数组。
为什么 Fisher-Yates shuffle 对这个数组起作用;
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var i = arr.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random()*(i+1));
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
console.log(arr);
但不是这个数组?
var Questions = [
new Question("What comes after 1?", ["1", "2","3", "4"], "2"),
new Question("What comes after 2?", ["1", "2", "3", "4"], "3"),
new Question("What comes after 3?", ["1", "2", "3", "4"], "4")
];
【问题讨论】:
-
欢迎来到 Stack Overflow!请使用tour(您将获得徽章!),环顾四周,并通读help center,尤其是How do I ask a good question?,我还推荐Jon Skeet 的Writing the Perfect Question 和Question Checklist。发帖前请search。更多关于搜索here。
-
这似乎已被关闭,因为有点快。当然,duplicate 有现代 Fisher-Yates shuffle 的代码。但这个问题是关于为什么它不适用于他的对象数组。
-
我看不出它为什么不能以同样的方式工作。您可以创建一个可运行的 sn-p 来显示该问题吗?您还没有真正共享受影响的代码,因此无法判断您做错了什么。
-
它在干净的环境中工作:repl.it/repls/DimgrayCourageousListeners(点击“运行”几次)。我认为您还需要为我们提供更多的东西。
标签: javascript arrays sorting shuffle