javascript - Javascript 中二维数组抛出异常

标签 javascript arrays

我想要一个带有二维数组的对象。它将包含带有相关选项和正确答案的问题。第一次通过它工作正常,但第二次 i= 1 k= 0 我得到一个异常。以下是在对象中第一个条目之后抛出异常的相关代码:

var testquestions = [{
        question:[],
        choices:[[]],
        answer:[],
       }
      ];
      var i = 0;

 $( "#opener" ).click(function() {
          $( "#dialog" ).dialog( "open" );
          $( "#dialog" ).dialog({
            minWidth: 700,
            minHeight: 650,
            buttons: [
                 {
                   text: "Add Question",
                   click: function() {
                       i = testquestions[0].question.length;
                       testquestions[0].question[i] = $( "#question" ).val();
                       for(var k = 0; k < 4; k++){
                           if ($("#" + k).val() != "")  {
                             alert("i and k values are " + i + "nd " + k);
                             testquestions[0].choices[i][k] = $( "#" + k ).val();
                           }
                        }  // for k
                      testquestions[0].answer[i] = $("#correctAnswer").val();
                      $("#test")[0].reset();
                      alert(testquestions[0].question[i]);
                    }
                 }

异常

TypeError: testquestions[0].choices[i] is undefined

testquestions[0].choices[i][k] = $( "#" + k ).val();

有人可以告诉我我是否正确声明和调用了二维数组?当 i = 1 时抛出异常。谢谢 更新:下面的答案确实解决了我的问题。

最佳答案

testquestions[0].choices[i]未定义(因为 choices:[[]] )并且从未分配,因此您无法使用 [k] 访问它。添加一个

testquestions[0].choices[i] = [];

正下方

testquestions[0].question[i] = $( "#question" ).val();

解决这个问题。

注释:

  • var foo = { choices:[[]] }相当于

    var foo = {};
    foo.choices = [];
    foo.choices[0] = [];
    

    它初始化 choices字段是一个只有一个元素的数组:一个空数组。所以,.choices[0]存在,但是choices[1]没有,这会导致 choices[1][k] 上出现错误。

  • Tou 可能想使用 console.log() (按F12查看)而不是alert() ,因为这在循环内部变得很烦人。 ;-)

  • 最好不要使用#1 。请参阅the note on this page :有一个id始终以字母开头。

  • 由于问题总是有一些 (4) 个选项,也许您可​​以使用以下结构:{ question: "?", choices: ["A","B","C"], answer: "C" }

    var testquestions = [];
    
    function addQuestion( q, c, a ) {
        testquestions.push( { question: q, choices: c, answer: a } );
    }
    

    和你的处理程序:

     click: function() {
                addQuestion( 
                    $( "#question" ).val(),
                    $( 'input.choice' ).map( function(i,e){ return $(e).val();}).get(),
                    $("#correctAnswer").val()
                );
    
                $("#test")[0].reset();
              }
    

    您需要更改 <input id='1'> ... <input id='4'><input class='choice'> .

更新

var testquestions = [{
        question:[],
        choices:[],
        answer:[],
       }
      ];
      var i = 0;

$( "#opener" ).click(function() {
   i = testquestions[0].question.length;
   testquestions[0].question[i] = $( "#question" ).val();
   testquestions[0].choices[i] = [];
   for(var k = 0; k < 4; k++){
     if ($("#c" + k).val() != "")  {
       testquestions[0].choices[i][k] = $( "#c" + k ).val();
     }
   }  // for k
   testquestions[0].answer[i] = $("#correctAnswer").val();
   console.log("Added question", testquestions[0] );
   $("#test")[0].reset();                      
 }
);
fieldset { display: inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dialog'>
  <form id='test'>
    Q <input id='question'/><br/>
    A <input id='correctAnswer'/><br/>
    C <fieldset label='foo' title='bar'>
    <input id='c0' class='choice'/><br/>
    <input id='c1' class='choice'/><br/>
    <input id='c2' class='choice'/><br/>
    <input id='c3' class='choice'/><br/>
    </fieldset>
    <button id='opener'>add question</button>
  </form>
</div>

关于javascript - Javascript 中二维数组抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35302890/

相关文章:

javascript - 添加两个列表进行选择,默认选择第一个

javascript - Vuejs Hello World 不会渲染

从函数 c 返回二维数组的正确方法

java - 删除数组[]元素

javascript - 抓取呈现的 JavaScript 网页

javascript - 将变量从 javascript 传递到 JSON POST - 获取非法 token

javascript - 使用 templateUrl 的单元测试指令有问题

c - c语言在内存中存储数组的机制是什么

javascript - 在 jQuery 中从 SerializeArray 获取值的最有效方法是什么?

javascript - 我有一个表单,它接受用户输入,创建一个新对象并推送到一个数组中。如何防止创建重复的对象?