Select 来自 JSON 的随机对象

Select random object from JSON

我有以下代码:

$.getJSON('js/questions1.json').done(function(data){
        window.questionnaire = data;
        console.log(window.questionnaire);
        startGame();
    });

这会从服务器获取一个 json 并将其记录到一个变量中。在此之后,我想 select questions.json 文档中的一个随机问题:

function pickRandomQuestion(){
        window.selectedquestion = window.questionnaire[Math.floor(Math.random * window.questionnaire.length)];
        console.log(window.selectedquestion);
        console.log(window.questionnaire);
    }

然而,当 console.log() selectedquestion 变量时,什么也没有返回,它是未定义的。我的代码有问题吗?我已经检查了三遍,没有发现任何问题,但这可能只是我的脑袋在玩游戏。

json 的外观如下:

"q1" : {
        "question" : "This country is one of the largest wine-producing countries of the world, where wine is grown in every region of the country. Which country is this?",
        "a"        : "France",
        "b"        : "Italy",
        "c"        : "Germany",
        "d"        : "Australia",
        "corrrect" : "b"
    },
    "q2" : {
        "question" : "What is the name for the type of art portrait that deliberately exaggerates a person?",
        "a"        : "Environmental",
        "b"        : "Cartooning",
        "c"        : "Caricature",
        "d"        : "Tribal",
        "corrrect" : "c"
    },
    "q3" : {
        "question" : "Who was the first president of the United States?",
        "a"        : "Abraham Lincoln",
        "b"        : "Ronald Reagan",
        "c"        : "George Washington",
        "d"        : "Barack Obama",
        "corrrect" : "c"
    }...

那是因为 math.random 不是 属性 的函数。

改为:Math.random()

并且因为 window.questionnaire 是一个对象,您无法使用索引访问它,即 (0,1,2)

你可以这样做:

function pickRandomQuestion(){
        var obj_keys = Object.keys(window.questionnaire);
        var ran_key = obj_keys[Math.floor(Math.random() *obj_keys.length)];
        window.selectedquestion = window.questionnaire[ran_key];
        console.log(window.selectedquestion);
        console.log(window.questionnaire);
}

我认为这应该可行

function pickRandomQuestion(){
    window.selectedquestion = window.questionnaire['q' + Math.floor(Math.random() * window.questionnaire.length)];
    console.log(window.selectedquestion);
    console.log(window.questionnaire);
}

无论何时从 json:

中获取数据,您都可以对数据进行随机排序

data.sort(function() { return .5 - Math.random();});

$.getJSON('js/questions1.json').done(function(data){
    window.questionnaire = data;
    window.questionnaire.sort(function() { return .5 - Math.random();});
    console.log(window.questionnaire);
    startGame();
});

然后,在pickRandomQuestion()中你可以只取window.questionnaire中的第一个元素,知道它是随机排序的。

注意:您也可以始终在 pickRandomQuestion() 例程中对列表进行随机排序,但我想您可能希望其中包含一些逻辑,这样相同的随机问题就不会像以前那样频繁出现随机,至少 pickRandomQuestion() 不会 return 与当前问题相同的问题。