如果我有这样的话:
var quiz = [{
"questionID": "KC2Q4",
"correctAnswer": "KC2Q4a"
},{
"questionID": "KC2Q5",
"correctAnswer": "KC2Q5b"
}];
并有一个我们可以调用的变量"问题"具有像KC2Q4这样的字符串值。如何退回" correctAnswer"对于" questionID"匹配变量"问题"在一个新的变量"回答"?
答案 0 :(得分:2)
您应该使用Array.prototype.filter
函数( note filter()
是一个ECMA-Script 5.x本机函数:您不需要第三方库或框架!! ):
var correctAnswer = "KC2Q4a";
// "filter" is like a "where". It iterates each object in your array
// and returns ones that fit the given condition as a closure:
var answersFound = quiz.filter(function(question) {
return question.correctAnswer == correctAnswer;
});
// You could verify if length > 0, but you want to be sure that
// there's only a single match for a given correct answer, because I feel
// that "correctAnswer" is like an unique id...
if(answersFound.length == 1) {
// Since there's a found answer to given "correctAnswer",
// you get the single result (i.e. the question object):
var answer = answersFound[0];
}
如果您发现上述检查无效(在我的情况下,我称之为防御性编程),您可以通过这种方式直接检索问题对象:
// Without the checking done in the other code listing, you've two risks:
// a. "quiz" could contain no question objects and the filter will return zero results
// meaning that getting first result array index will throw an error!
//
// b. "quiz" could contain question objects but what you're looking for isn't
// present in the so-called array. Error too!
var answer = quiz.filter(function(question) {
return question.correctAnswer == correctAnswer;
})[0];
答案 1 :(得分:2)
你基本上想迭代你的数组,检查每个对象是否有正确的questionID。找到该对象后,返回该对象的correctAnswer属性。
var question = "KC2Q4";
for( var i=0; i<quiz.length; i++ ){
if( quiz[i].questionID === question ){
return quiz[i].correctAnswer;
}
}