2D javascript数组返回" undefined"

时间:2016-10-27 17:40:40

标签: javascript arrays multidimensional-array

我在JavaScript中初始化了一个2D数组:

var staffOnAfternoonDuties = [];
staffOnAfternoonDuties['5'] = [];
staffOnAfternoonDuties['5'][0] = 0;
staffOnAfternoonDuties['5'][1] = 0;
staffOnAfternoonDuties['5'][2] = 0;
staffOnAfternoonDuties['5'][3] = 0;
staffOnAfternoonDuties['5'][4] = 0;
...
staffOnAfternoonDuties['8'][3] = 0;
staffOnAfternoonDuties['8'][4] = 0;

我试图从这个选择框中访问数组中的值,在这个jQuery方法中:

<select id="PM_0_6" class="Monday">
    <option></option>
    <option value="5">Vacuum</option>
    <option value="6">Polishing</option>
    <option value="7">Elevators / Mail</option>
    <option value="8">Garage</option>                        
</select>


$("#PM_0_6").change(function(){
    var duty = $(this).val();
    var dayNumber = parseInt($(this).attr("id").substring(3,4));
    var previous = parseInt($(this).data('pre'));
    staffOnAfternoonDuties[previous][dayNumber]--;
    switch(dayNumber){
        case 0:
            day = "Monday";
            break;
        case 1:
            day = "Tuesday";
            break;
        case 2:
            day = "Wednesday";
            break;
        case 3:
            day = "Thursday";
            break;
        case 4:
            day = "Friday";
            break;
    }
    $("." + day +".ad" + duty).css("color", "green");
    staffOnAfternoonDuties[$(this).val()][dayNumber]++;
    $("." + day +".ad" + previous).text("("+staffOnAfternoonDuties[previous][dayNumber]+")");
    $("." + day +".ad" + duty).text("("+staffOnAfternoonDuties[duty][dayNumber]+")");

    $(this).data('pre', $(this).val());
});

当我执行此操作时,我收到此错误:

VM74:2011 Uncaught TypeError: Cannot read property '0' of undefined

哪些引用回到此行(以及尝试访问2D数组的所有其他行):

staffOnAfternoonDuties[previous][dayNumber]--;

当我记录previous和dayNumber时,我得到了值。当我记录数组时,它以预期的形式显示对象。为什么我不能使用这些变量访问它?

2 个答案:

答案 0 :(得分:0)

我认为你的阵列初始化是这里的问题。 JavaScript中的数组需要整数索引,而不是字符串。没有完整的代码可以判断,但如果从第一级数组索引中删除引号,它可能会有效。

答案 1 :(得分:0)

$(this).data(&#39; pre&#39;)将始终返回undefined cause select没有属性data-pre。