从JSON中选择随机对象

cod*_*nja 4 javascript random jquery json

我有以下代码:

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

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

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

但是,当console.log()selectquestion变量没有返回时,它是未定义的.我的代码有问题吗?我已经三倍检查它,我看到它没什么不好,但它可能只是我和我一起玩游戏.

以下是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"
    }...
Run Code Online (Sandbox Code Playgroud)

Oma*_*ady 7

那是因为math.random功能不是属性.

将其更改为: Math.random()

并且becuase 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);
}
Run Code Online (Sandbox Code Playgroud)