javascript 从 JSON 中选择随机对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30061969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:36:17  来源:igfitidea点击:

Select random object from JSON

javascriptjqueryjsonrandom

提问by codeninja

I have the following code:

我有以下代码:

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

This brings a json from the server and logs it into a variable. Now after this, I want to select a random question located in the questions.json document:

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

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

However, when console.log()the selectedquestion variable, nothing comes back, it's undefined. Is there something wrong with my code? I've tripled checked it and I see nothing bad on it, but it might just be my head playing games with me.

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

Here's how the json looks:

这是 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"
    }...

回答by Omar Elawady

That's because math.randomis function not a property.

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

Change it to: Math.random()

将其更改为: Math.random()

and becuase window.questionnaireis an object you can't access it using indexes i.e(0,1,2)

因为window.questionnaire是一个对象,你不能使用索引访问它 ie(0,1,2)

you can do this:

你可以这样做:

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);
}

回答by Alan Files

You can sort the data randomly whenever you get it from the json:

每当您从 json 中获取数据时,您都可以对数据进行随机排序:

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

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();
});

Then, in the pickRandomQuestion()you can just take the first element in window.questionnaire, knowing that it was randomly sorted.

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

Note: you could also always randomly sort the list inside the pickRandomQuestion()routine, but I imagine you might want some logic in there so that the same random question doesn't come up as often as it would randomly, or so at least pickRandomQuestion()won't return the same question as the current one.

注意:您也可以始终在pickRandomQuestion()例程中随机对列表进行排序,但我想您可能需要一些逻辑,以便相同的随机问题不会像随机问题那样经常出现,或者至少pickRandomQuestion()不会返回与当前问题相同的问题。

回答by pieperz

I think this should work

我认为这应该有效

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