从JSON中选择随机对象 [英] Select random object from JSON

查看:91
本文介绍了从JSON中选择随机对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

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:

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

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

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.

以下是json的外观:

Here's how the json looks:

"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 是函数而不是属性。

That's because math.random is function not a property.

将其更改为: Math.random()

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

and becuase window.questionnaire is an object you can't access it using indexes i.e(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);
}

这篇关于从JSON中选择随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆