有人可以为我解释这个循环吗?它是自由代码阵营中罗马数字挑战的一部分 - 它不是我的,我做了我自己的,但它是更多的代码。我正在努力了解这一点以改善我自己。无论如何,while循环完全抛弃了我。任何帮助都会很棒。
function romans(num){
var roman = "";
var romanNumerals = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"];
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
for (var i=0; i<numbers.length; i++) {
//If the num was 5 then then it would read 5 greater than 1000?
while (num >= numbers[i]) {
roman = roman + romanNumerals[i]
//5 minus 1000?
num = num - numbers[i]
}
}
return roman;
}
console.log(romans(5))
答案 0 :(得分:1)
num
作为所需的输入开始,然后您会找到加起来为num
的数字,从最大的罗马数字(numbers[0]
)开始。
您使用while循环重复,因为您可能需要多个字母副本(即"III" == 3
)
romans(5)
在numbers[10]
之前不会触发while循环(因为正如你所说5 >= 1000 == false
),此时你将字符V追加到roman
,并减去5来自num
。由于num
现在为0,因此while循环将永远不会再触发。
尝试使用romans(3001)
进行思考,你会看到m / 1000的while循环触发3次,然后跳过10次,然后触发I / 1
答案 1 :(得分:1)
function romans(num){
var roman = "";
var romanNumerals=["M","CM","D","CD","C","XC","L","XL","X",
"IX","V","IV","I"];
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
for (var i=0; i<numbers.length; i++){
//If the num was 5 then then it would read 5 greater than 1000?
console.log("comparing: " + numbers[i]);
console.log(" with: " + num);
while(num >= numbers[i]){
console.log("entered");
roman = roman + romanNumerals[i]
//5 minus 1000?
num = num - numbers[i]
console.log('subtracting: ' + numbers[i]);
}
}
return roman
}
console.log(romans(44))
它将沿着数字线向下,直到找到一个更小的数字:例如44:
在for for it中它将遍历数字数组,直到它找到一个数字然后是44(在迭代之前永远不会输入while循环)。
当它找到一个小于44的数字时,它进入while循环并在该迭代中取i的位置处的romanNumerals,在这种情况下为40.然后它将原始数字降低40(44-40 = 4)并且然后退出循环返回到for以搜索低于4的数字。