Javascript:定义了2d数组,但是将2d数组的元素分配给变量时,它变为“未定义”

时间:2019-06-12 14:23:20

标签: javascript google-chrome-extension

我正在创建Google Chrome扩展程序并使用Javascript。打印2d数组的元素时,它工作得很好。但是,当我将该元素设置为变量时。它给出了这个错误,

  

错误处理响应:TypeError:无法读取未定义的属性“ 3”

我建立了调试语句,清楚地表明2d数组不是未定义的。但是,将元素分配给变量会使它变得不确定。

previous_data = [
    ["AP Micro Economics ", 95.8, 94.1, 95.2, 95.4],
    ["IB Literature_Language I HL ", 95.9, 93.6, 98.4, 95.4],
    ["AP Calculus AB ", 97.5, 93.9, 98.5, 96.6],
    ["Adv Topics Comp Science ", 98.3, 96.3, 93, 95.7],
    ["Physics ", 95, 99.1, 94.9, 96.3],
    ["Simulations and Num Models ", "N", 95, "N", "N"],
    ["IB Hist of Amer I HL ", 94.2, 93.9, 92.2, 93.4],
    ["IB Espanol IV SL ", 96.1, 95.4, 92.1, 94.5],
    ["Structured Query Lang ", "N", 98.6, "N", "N"],
    ["Artificial Intelligence ", "N", "N", 91.8, "N"]
];
for (subject = 0; subject < 1; subject++){
    for (section = 1; section < current_data[subject].length; section++){
        if (previous_data[subject][section] != current_data[subject][section]){
            // These print properly
            console.log("previous_data");
            console.log(previous_data);
            //This prints properly
            var subject = previous_data[subject][0];
            console.log(subject)
            // This is where the code breaks
            var before = previous_data[section];
            console.log(previous_data[subject][section])
        }
    }
}

您知道为什么 previous_data 被读取为未定义吗?

1 个答案:

答案 0 :(得分:0)

您两次使用subject作为变量。您必须区分变量值和变量索引。

for (subjectIndex = 0; subjectIndex < 1; subjectIndex++){
    for (sectionIndex = 1; sectionIndex < current_data[subjectIndex].length; sectionIndex++){
        if (previous_data[subjectIndex][sectionIndex] != current_data[subjectIndex][sectionIndex]){
            // These print properly
            console.log("previous_data");
            console.log(previous_data);
            //This prints properly
            var subject = previous_data[subjectIndex][0];
            console.log(subject + " at index [" + subjectIndex + "][0]");
            // This is where the code breaks
            var before = previous_class[sectionIndex];
            console.log(previous_data[subjectIndex][sectionIndex])
        }
    }
}