eclectic324
eclectic324

Reputation: 33

Keep getting undefined when calling 2 dimensional array in JS

So I'm currently making a bit of script that will take in a value between 0 and 3999 and pump out the roman numerals for the number. For some reason when calling my 2 dimensional array, I wind up getting undefined

            function romanConverter() {
                var romanOutput;
                var enteredNum = prompt('What number would you like converted between 1 and 3999?');
                var romanNum = [
                    ['', 'M', 'MM', 'MMM'], // Thousands place
                    ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'], // Hundreds place
                    ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], // These are for the tens place
                    ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'] // Ones place 
                ];

                if (parseInt(enteredNum) > 3999) {
                    alert("I'm sorry that's not a valid entry");
                    enteredNum = prompt('What number would you like converted between 1 and 3999?');
                } else {
                    while (enteredNum.length < 4) {
                        enteredNum = '0' + enteredNum;
                    }
                    for (var i = 0; i <= enteredNum.length; i += 1) {
                        var currentNum = parseInt(enteredNum.charAt(i));
                        romanOutput += romanNum[i][currentNum];
                    }
                }
                document.write(romanOutput);
            }
            romanConverter();

I always get the TypeError: romanNum[i] is undefined I'm really stuck and could use some help.

Upvotes: 3

Views: 65

Answers (1)

johnnyRose
johnnyRose

Reputation: 7490

This is one of those sneaky little errors that always makes you bang your head against a wall for a while.

Try changing your final for loop to the following:

for (var i = 0; i < enteredNum.length; i += 1) { // etc...

You want strictly less than - not less than or equal to. Otherwise, you'll end up evaluating something like "05".charAt(2);

To prevent its output from being undefined followed by the converted roman numeral, you will also want to change the line that says

var romanOutput;

To

var romanOutput = "";

Upvotes: 3

Related Questions