我正在尝试从freeCodeCamp进行罗马数字挑战。我不知道为什么会出现以下错误:
if(numKey [i] [0] <=剩余){ TypeError:无法读取未定义的属性“ 0”
这是我的代码:
function convertToRoman(num) {
const numKey = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50,'L'], [40, 'XL'], [10, 'X'], [9, 'IX'] [5, 'V'], [4, 'IV'] [1, 'I']];
let remaining = num;
let romanStr = '';
while(remaining > 0) {
for(let i = 0; i < numKey.length; i++) {
if(numKey[i][0] <= remaining) {
let j = 0;
while(j < Math.floor(remaining/numKey[i][0])) {
romanStr += numKey[i][1]
remaining -= numKey[i][0] * Math.floor(remaining/numKey[i][0])
j++
}
}
}
break;
}
return romanStr;
}
我不知道为什么numKey[i][0]
是不确定的。据我所知,它永远不会超出范围,当我在上一行中执行console.log(numKey[i][0])
时,它始终会打印正确的值。有什么我想念的吗?
谢谢!
答案 0 :(得分:2)
您的循环是正确的。但是数组错了,在最后两个数组中缺少一些export PATH=$PATH:/user/bin;/Applications/MiKTeX Console.app/Contents/bin/cjklatex
,
无效
在以下代码段中检查此内容。查看其未定义的
[9, 'IX'] [5, 'V'], [4, 'IV'] [1, 'I']
const numKey = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50,'L'], [40, 'XL'], [10, 'X'], [9, 'IX'] [5, 'V'], [4, 'IV'] [1, 'I']];
console.log(numKey)
答案 1 :(得分:0)
我认为您的代码中只有一个错字,numKey数组的格式不正确:
尝试:
function convertToRoman(num) {
const numKey = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50,'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
let remaining = num;
let romanStr = '';
while(remaining > 0) {
for(let i = 0; i < numKey.length; i++) {
if(numKey[i][0] <= remaining) {
let j = 0;
while(j < Math.floor(remaining/numKey[i][0])) {
romanStr += numKey[i][1]
remaining -= numKey[i][0] * Math.floor(remaining/numKey[i][0])
j++
}
}
}
break;
}
return romanStr;
}
console.log(convertToRoman(133));
console.log(convertToRoman(42));