Two dimentional array in js

时间:2015-06-26 10:21:20

标签: javascript jquery arrays

I am trying to get a two dimensional array in Javascript, but I have a json and from that I am trying to populate a 2D array. My code is here:

jQuery.each(data.data, function(key,val){
        survey_sec_id_arr.push(val.section_id);
        survey_question_id_arr.push(val.section_id);
        jQuery.each(val, function(key1,val1){
            if(key1!="section_id" && key1!="section_name"){ 
                survey_question_id_arr[val.section_id].push(val1.question_id);
            }
        });
});
console.log(survey_question_id_arr);

So here the error in firebug is:

TypeError: survey_question_id_arr[val.section_id] is undefined

What is going wrong?

2 个答案:

答案 0 :(得分:2)

你循环不正确。您可以通过push添加所有这些元素,因此您的数组看起来像

survey_question_id_arr = array( [0] => val.section_id, [1] => val.section_id...)

然后你尝试通过

获取这个数组的元素
//returns undefined
survey_question_id_arr[val.section_id]

//should return a value
val.section_id[0]

修正:

survey_question_id_arr[val.section_id].push(val1.question_id)

我认为这解决了问题

答案 1 :(得分:0)

您可以推送数组中的值。

我猜你的var val.section_id不是数组。我们可以在数组中推送值。所以首先将它初始化为Empty数组,如:

survey_question_id_arr[val.section_id] = [];

(在内循环之前声明它)

然后尝试推动其中的价值。

survey_question_id_arr[val.section_id].push(val1.question_id)

希望它有所帮助。