将其他数组中的数组插入到for循环中,首先重复结果

时间:2013-01-05 16:44:49

标签: javascript arrays for-loop multidimensional-array

在此循环中将数组插入另一个数组时遇到问题:

function formToArray(frm){
    var sAux={};
    var AnnotationsQuestion={};
    var AllAnnotationsQuestion=[];

    for (i = 0; i < frm.length; i++) {

    //next line dont work
    sAux['question_id'] = frm[i].name.substring(13)
    sAux['answer']=frm[i].value;
    sAux['id']=0;
    AnnotationsQuestion['AnnotationsQuestion']=sAux;
    AllAnnotationsQuestion.push(AnnotationsQuestion);
    }

return AllAnnotationsQuestion 
}

这会返回重复x次的第一个结果

返回值的示例

[{'AnnotationsQuestion':{'question_id':4,'answer':
'AA'....}},{'AnnotationsQuestion':{'question_id':4,'answer':
'AA'....}}]

这个循环有什么问题?

1 个答案:

答案 0 :(得分:2)

这更加安全和可读

DEMO

function formToArray(frm){
  var AllAnnotationsQuestion=[];

  for (var i = 0; i < frm.length; i++) {
    AllAnnotationsQuestion.push({
      'AnnotationsQuestion': {
        'question_id': frm[i].name.substring(13),
        'answer': frm[i].value, 
        'id':0 
      }
    });
  }
  return AllAnnotationsQuestion; 
}