javascript访问数组中的对象

javascript访问数组中的对象,javascript,Javascript,如果我有这样的东西: var quiz = [{ "questionID": "KC2Q4", "correctAnswer": "KC2Q4a" },{ "questionID": "KC2Q5", "correctAnswer": "KC2Q5b" }]; 还有一个变量,我们可以称之为“question”,它的值是一个字符串,比如KC2Q4。如何为与新变量“answer”中的变量“question”匹配的“questionID”返回“correctAnsw

如果我有这样的东西:

var quiz = [{
    "questionID": "KC2Q4",
    "correctAnswer": "KC2Q4a"
},{
    "questionID": "KC2Q5",
    "correctAnswer": "KC2Q5b" 
}];
还有一个变量,我们可以称之为“question”,它的值是一个字符串,比如KC2Q4。如何为与新变量“answer”中的变量“question”匹配的“questionID”返回“correctAnswer”?

您应该使用函数(注意
filter()
是ECMA脚本5.x本机函数:您不需要第三方库或框架!!):

如果您发现上述检查没有用(在我的情况下,我称之为防御编程),您可以通过以下方式直接检索问题对象:

// 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];
您应该使用函数(注意
filter()
是ECMA脚本5.x本机函数:您不需要第三方库或框架!!):

如果您发现上述检查没有用(在我的情况下,我称之为防御编程),您可以通过以下方式直接检索问题对象:

// 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];

基本上,您希望在数组上迭代,检查每个对象是否具有正确的questionID。找到该对象后,返回该对象的correctAnswer属性

var question = "KC2Q4";
for( var i=0; i<quiz.length; i++ ){
  if( quiz[i].questionID === question ){
    return quiz[i].correctAnswer;
  }
}
var-question=“KC2Q4”;

对于(var i=0;i,您基本上希望在数组中迭代,检查每个对象是否有正确的questionID。找到该对象后,返回该对象的correctAnswer属性

var question = "KC2Q4";
for( var i=0; i<quiz.length; i++ ){
  if( quiz[i].questionID === question ){
    return quiz[i].correctAnswer;
  }
}
var-question=“KC2Q4”;

对于(var i=0;这正是您要找的。是的,这正是我要找的!谢谢。在我发布之前,我在搜索中没有找到该帖子。:/这就是您要找的。是的,这正是我要找的!谢谢。在我发布之前,我在搜索中没有找到该帖子。/@zerkms我打算这样做。我已经用你的建议更新了我的答案。@zerkms顺便说一句,我已经更新了你建议的优点/缺点:D@zerkms我本来打算这样做的。我已经用你的建议更新了我的答案。@zerkms顺便说一句,我已经更新了你建议的利弊:D