简体   繁体   English

2D JavaScript数组返回错误“ undefined”

[英]2D javascript array returns the error of “undefined”

I have a 2D array initialized in JavaScript: 我有一个用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;

I am trying to access the values in the array from this select box, inside this jQuery method: 我正在尝试从此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());
});

When I execute this, I get this error: 执行此操作时,出现以下错误:

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

Which references back to this line (and all other lines trying to access the 2D-array): 哪些引用返回此行(以及所有其他尝试访问2D数组的行):

staffOnAfternoonDuties[previous][dayNumber]--;

When I log previous and dayNumber, I get values back. 当我记录上一个和dayNumber时,我会返回值。 When I log the array, it displays the object in the expected form. 当我记录数组时,它将以预期的形式显示对象。 Why can I not access it using these variables? 为什么不能使用这些变量访问它?

I think it's your array initialisation that's the problem here. 我认为这是您的阵列初始化问题。 Arrays in JavaScript need an integer index, not a string. JavaScript中的数组需要整数索引,而不是字符串。 It's hard to tell without having the full code to look at, but if you remove the quotes from the first level array indexes, it might work. 没有完整的代码就很难知道,但是如果您从第一级数组索引中删除引号,它可能会起作用。

$(this).data('pre')将始终返回未定义的原因,因为select没有data-pre属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM