从 JSON 中选择随机对象 [重复]
Posted
技术标签:
【中文标题】从 JSON 中选择随机对象 [重复]【英文标题】:Select random object from JSON [duplicate] 【发布时间】:2015-07-15 17:14:10 【问题描述】:我有以下代码:
$.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"
...
【问题讨论】:
【参考方案1】:那是因为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);
【讨论】:
【参考方案2】:只要从 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()
不会返回与当前问题相同的问题。
【讨论】:
啊,没有意识到您的 json 没有作为数组返回。这可能没有那么有用:)【参考方案3】:我认为这应该可行
function pickRandomQuestion()
window.selectedquestion = window.questionnaire['q' + Math.floor(Math.random() * window.questionnaire.length)];
console.log(window.selectedquestion);
console.log(window.questionnaire);
【讨论】:
看起来window.questionnaire
不会有length
属性。你可能需要做类似Object.keys(window.questionnaire).reduce(function (length, key) return length + (window.questionnaire.hasOwnProperty(key) ? 1 : 0); , 0)
以上是关于从 JSON 中选择随机对象 [重复]的主要内容,如果未能解决你的问题,请参考以下文章