Keep getting undefined when calling 2d array in JS

So I am currently doing a little script that will take a value between 0 and 3999 and pump out roman numerals for a number. For some reason, when calling my 2-dimensional array, I end 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 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 TypeError: romanNum[i] is undefined

, I am really stuck and could use some help.

+3


source to share


1 answer


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

Try changing the end loop for

to this:

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

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



To eliminate its output undefined

followed by a converted roman numeral, you will also want to change the line that says

var romanOutput;

      

For

var romanOutput = "";

      

+3


source







All Articles