3

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.

1 Answer 1

3

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 = "";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this was incredibly helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.