简体   繁体   中英

Javascript: 2d array is defined, but when assigning an element of the 2d array to a variable, it becomes 'undefined'

I'm creating a Google Chrome extension and working with Javascript. When printing an element of a 2d array, it works perfectly fine. However, when I set that element to a variable. It gives this error,

Error handling response: TypeError: Cannot read property '3' of undefined

I've set up debugging statements that clearly show that the 2d array is not undefined. But assigning an element to a variable makes it undefined somehow.

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])
        }
    }
}

Any idea why previous_data is being read as undefined?

You are using subject as a variable twice. You have to differentiate between the variable value and the variable index.

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])
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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