Roman Numerals help

Roman Numerals help
0

#1

Hey.
A “num” should be equal to romanKeys. Roman keys is a massive (right?) so I have to turn it into a string to compare. But somehow it doesn’t work. What have I done wrongly?
Code:

function convertToRoman(num) {
  var roman = {
   1:'I',
   2:'II',
    3: 'III',
    4: 'IV',
    5: 'V',
    6: 'VI',
    7: 'VII',
    8: 'VIII',
    9: 'XI',
    10: 'X'
  };
  var x;
 var romanKeys = Object.keys(roman)[1].toString();
  if (num === romanKeys) //this should be true
    {return roman[1];}
  else return false;
}

convertToRoman(2);

#2

Your comparison below is comparing a number (num) to a string (romanKeys), so when you use the === it, the statement evaluates to false. If you use == instead it will evaluate to true in this example.

num === romanKeys

Review the following FCC challenges for help with these two different comparison operators.

Comparison with the Equality Operator

Comparison with the Strict Equality Operator


#3

Thanks, that work!
But I have yet another problem - I can’t get info from the for loop (even if the loop isn’t actually “working”). Variable “x” stays empty for some reason. Could you pls take a look?
Code:


function convertToRoman(num) {
  var roman = {
   1:'I',
   2:'II',
    3: 'III',
    4: 'IV',
    5: 'V',
    6: 'VI',
    7: 'VII',
    8: 'VIII',
    9: 'XI',
    10: 'X'
  };
  var x=[]; //this x should cointain roman[2], and it works without the for loop
 for (var i=0;i<roman.length;i++){
 var romanKeys = Object.keys(roman)[1];
  if (num == romanKeys)  {
      x.push( roman[2]);
    }
 }
return x.toString();  
}

convertToRoman(2);


#4

As currently written, roman is an object and not an array. When you type roman.length, JS looks for a property called “length”, so it returns undefined, because it does not have that property. If you want to loop through the roman object to have access to the keys/values, then you could do something like:

function convertToRoman(num) {
  var roman = {
   1:'I', 2:'II', 3: 'III', 4: 'IV', 5: 'V',
    6: 'VI', 7: 'VII', 8: 'VIII', 9: 'XI', 10: 'X'
  };
  var x=[]; //this x should cointain roman[2], and it works without the for loop

  for (var key in roman){
    // console.log(key, roman[key])   uncomment to see each key and value pair
    var romanKeys = Object.keys(roman)[1];
    if (num == romanKeys)  {
      x.push( roman[2]);
    }
  }
  return x.toString();  
}

convertToRoman(2);

However, the above is just going to create a string that looks like:

'II,II,II,II,II,II,II,II,II,II'

because on every iteration of the roman object, num is still 2 and romanKeys is still ‘2’, so the if statement will evaluate to true each time and the roman numeral II will get pushed on the the array (x).

You might want to review how to iterating through arrays and objects as you work on this challenge.