I am currently studying Data Structure & Algorithm in LeetCode. I tried to solve by myself 'Roman to integer number'. I tried to make an object, and accessing key and key's value by using for ...in. So, I want to check my key and key's value by using console.log but it didn't show anything. Could you check which part do I miss? I am sorry if I ask a stupid question. I tried to solve this by myself but I couldn't find where I did mistake for few hours... please Let me know if there is another mistake!
Here is code what I did so far
function romanToNum(s) {
const roman = {
I :1,
IV:4,
V :5,
IV:9,
X :10,
// IL: 49,
L :50,
// IC:99,
C :100,
// ID:499,
D :500,
// IM:999,
M :1000
};
let answer = '';
for(let key in roman){
console.log(key);
console.log(roman[key]);
while (s >= roman[key]) {
answer += key;
s -= roman[key];
}
}
}
You don't see anything because the object is not known whenever you are in the for loop block. In order to initialize the object and see it outside the local scope of the function romanToNum
, what you can do is the following thing.
You can either initialize the object globally, without enclosing it in the local scope of the function; basically get rid of romanToNum since it doesn't do anything anyway.
Return the object from the function and capture it in a global var.
function getObject() {
return roman = {
I :1,
IV:4,
V :5,
IV:9,
X :10,
// IL: 49,
L :50,
// IC:99,
C :100,
// ID:499,
D :500,
// IM:999,
M :1000
};
let roman = getObject();
I m not sure why you re choosing to do it this way, but it doesn't seem the most preferred one in my opinion.