如何Fisher-Yates随机播放JavaScript数组?

问题描述 投票:0回答:3

我正在尝试从Awais Mirza的教程中修改此测验应用程序>

我想从主数组中随机选择问题,并将其推入脚本用来填充问题的选择数组,因此,每次测验为时,测验将从主数组中随机抽取一组问题跑。我以为我可以先使用Fisher-Yates随机播放将主数组随机化,然后再将选定数量的问题放入选择数组中。

为什么Fisher-Yates随机播放对此数组起作用;

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")
];

我正在尝试从Awais Mirza的教程中修改此测验应用程序,我想从主阵列中随机选择问题,并将其推入脚本用于...的选择阵列中。]

javascript arrays sorting shuffle
3个回答
0
投票

randojs.com可能会更容易一点,它使用这种改组方法,但完全是首选。


0
投票

Fisher-Yates算法专用于数组索引,因此根据数组内容,您不需要不同的实现


-1
投票

我对此很喜欢:

© www.soinside.com 2019 - 2024. All rights reserved.