I want to know why my code doesn’t function as an answer.
Code:
const array=[ ];
function convertToRoman(num){
const romanNumbers=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
const romanDigits=[1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
for(let i=0;i<romanDigits.length;i++){
while(num>=romanDigits[i]){num-=romanDigits[i];
array.push(romanNumbers[i]);
};
}
console.log(array);
return array;}
Pedro_Aznar:
const array=[ ];
function convertToRoman(num){
const romanNumbers=["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
const romanDigits=[1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
for(let i=0;i<romanDigits.length;i++){
while(num>=romanDigits[i]){num-=romanDigits[i];
array.push(romanNumbers[i]);
};
}
console.log(array);
return array;}
Let me format this for human readability.
const array = [];
function convertToRoman(num) {
const romanNumbers = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
const romanDigits = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
for (let i=0;i<romanDigits.length;i++) {
while (num>=romanDigits[i]) {
num -= romanDigits[i];
array.push(romanNumbers[i]);
};
}
console.log(array);
return array;
}
That global variable holding the array is a problem. You shouldn’t change a global variable while your function executes. Your function will only run once.
Also, you need to return a string, not an array.
system
Closed
February 14, 2023, 2:37am
4
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.