user2364737
user2364737

Reputation: 21

type error undefined in javascript

I just learned about JavaScript and here is my script:

var now = new Date();
var date = now.getDate();
var month = now.getMonth();
var Holidays = [
    [8, 3],
    [9, 8],
    [10, 16],
    [11, 7],
    [11, 24],
    [11, 25],
    [11, 26],
    [11, 27],
    [11, 28],
    [11, 29],
    [11, 30],
    [11, 31],
    [0, 1],
    [0, 2],
    [0, 3],
    [0, 4],
    [0, 31],
    [1, 15],
    [1, 18],
    [2, 11],
    [2, 12],
    [2, 13],
    [2, 14],
    [2, 15],
    [2, 29],
    [3, 1],
    [4, 20],
    [5, 26],
    [5, 27],
    [5, 28]
];
var i = 0;
while (i <= Holidays.length) {
    if (check() === true) {
        console.log("No school today.");
        i = 32;
    } else if (check() === false) {
        if (i < Holidays.length) {
            i++;
        } else {
            console.log("we work today.");
            i++;
        }
    }
}

function check() {
    if (month == Holidays[i][0] && date == Holidays[i][1]) {
        return true;
    } else {
        return false;
    }
}

The purpose is to make it print out "No school today" for the days in the holiday array, otherwise, it'd print out "we work today". Whenever I run the script it always says

type error Holidays[i] undefined

Can someone help me with this?

Upvotes: 0

Views: 218

Answers (2)

Geeky Guy
Geeky Guy

Reputation: 9399

The last time the code does an i++, i will end up with a value that is the last index of Holidays + 1.

So in the line that throws an error, you're trying to retrieve an item that's not in the array. You're not trying to get a specific element of the array and the offending code is not in a loop, so you might want to check that.

Upvotes: 1

diwatu
diwatu

Reputation: 5699

At least one problem in your code

while (i <= Holidays.length) {

the last i should be Holidays.length-1, so use:

while (i < Holidays.length) {

Upvotes: 1

Related Questions