Javascript 从JSON中选择随机对象
我有以下代码:Javascript 从JSON中选择随机对象,javascript,jquery,json,random,Javascript,Jquery,Json,Random,我有以下代码: $.getJSON('js/questions1.json').done(function(data){ window.questionnaire = data; console.log(window.questionnaire); startGame(); }); 这将从服务器带来一个json并将其记录到一个变量中。接下来,我想选择位于questions.json文档中的一个随机问题: function pickRand
$.getJSON('js/questions1.json').done(function(data){
window.questionnaire = data;
console.log(window.questionnaire);
startGame();
});
这将从服务器带来一个json并将其记录到一个变量中。接下来,我想选择位于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()
因为窗口。问卷是一个对象,您不能使用索引(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(函数(){return.5-Math.random();})代码>
然后,在pickRandomQuestion()
窗口中,您只需获取窗口中的第一个元素。问卷
,知道它是随机排序的
注意:您也可以在pickRandomQuestion()
不会返回与当前问题相同的问题。它看起来不像窗口。调查问卷将具有长度属性。您可能需要执行类似于Object.keys(window.inventory).reduce(function(length,key){return length+(window.inventory.hasOwnProperty(key)?1:0);},0)
Ah,没有意识到json没有作为数组返回。这可能没有那么有用:)
$.getJSON('js/questions1.json').done(function(data){
window.questionnaire = data;
window.questionnaire.sort(function() { return .5 - Math.random();});
console.log(window.questionnaire);
startGame();
});