Javascript/HTML 中的罗马数字到数字的转换

Roman Numeral to Number Conversion in Javascript/HTML

我是 javascript 的新手,我想制作一个 html 文件来显示超级碗 "LIV" 前的天数、当前时间和输入用户将罗马数字转换为数字。我的代码在下面,就像现在一样,启动文件时不会出现倒计时元素和时间元素。但是,当我删除为转换罗马数字而创建的函数时,这两个元素再次出现。这告诉我我的代码的问题出在这些函数中,但是我找不到 what/where 需要解决的问题,或者我是否采用了错误的方法来进行转换。 I'm wanting the user to type in a roman numeral to the rn text input and when the "Convert" button input is selected, the corresponding number appears in the result span.我需要使用函数 "toNumber()" 中使用的算法的概念,但是我显然可能在此过程中实现了一些错误。任何帮助表示赞赏。

<html>
<head>
    <title>Roman Numeral Converter</title>
</head>
<body>
<div> 
    <p id="countdown"></p>
    <p id="time"></p>
    <p> Please enter a Roman number (e.g. LIV) to convert to a number: </p>
    <form action="PayslipServlet" method="get">
        <input type="text" name="romannumber" id="rn"> => <span id="result"></span>
        <br>
        <input type="button" value="Convert" onClick="toNumber()"> <input type="button" value="Reset" onclick="empty()">
    </form>
</div>
<script type="text/javascript">

        function sbCountdown() {

            var countdownDate = new Date("February 2, 2020").getTime();

            var now = new Date();
            var rn = now.getTime();

            var daysLeft = countdownDate - rn;

            var days = Math.floor(daysLeft / (1000 * 60 * 60 * 24));

            document.getElementById("countdown").innerHTML = "There are " + days + " days until SUPER BOWL LIV 2020 (February 2, 2020)";

            if(daysLeft < 0) {
                document.getElementById('countdown').innerHTML = "EXPIRED";
            }

            setTimeout(sbCountdown, 1000);
        }

    sbCountdown();


    function updateClock() {

        var now = new Date(), // current date
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var dateString = "*** The Current Time is: ";
        var hh = now.getHours();
        var dd = "AM";
        var h = hh;
        if(h >= 12 ) {
            h = hh - 12;
            dd = "PM";
        }
        if( h == 0 ) {
            h = 12;
        }
        time = h + ':' + now.getMinutes() + ':' + now.getSeconds() + " " + dd; 

        // a cleaner way than string concatenation
        date = [now.getDate(), 
            months[now.getMonth()],
            now.getFullYear()].join(' ');

        // set the content of the element with the ID time to the formatted string
         document.getElementById('time').innerHTML = dateString + date + " , " + time;

        // call this function again in 1000ms
        setTimeout(updateClock, 1000);
    }

    updateClock();


    function getValue(s) {

        var num = 0;

        if(s == 'I') { num = 1 }
        else if(s == 'V') { num = 5 }
        else if(s == 'X') { num = 10 }
        else if(s == 'L') { num = 50 }
        else if(s == 'C') { num = 100 }
        else if(s == 'D') { num = 500 }
        else if(s == 'M') { num = 1000 }
        else { document.getElementById(result).innerHTML = "Not a Roman Numeral" }

        return num;
    }

    function toNumber() {

        var total = 0;
        var romNum = document.getElementById(rn).value
        var number;


        while(romNum != "") {

            if(getValue(romNum.charAt(0)) >= getValue(romNum.charAt(1)) || romNum.length() == 1) {

                number = getValue(romNum.charAt(0));
                total += number;

                var temp = romNum.slice(1);
                romNum = temp;
            }
            else {

                number = getValue(romNum.charAt(1) - getValue(romNum.charAt(0));
                total += number;

                var temp = ronNum.slice(2);
                ronNum = temp;
            }

        }

        document.getElementById(result).innerHTML = total;
    }


</script>

</body>
</html>

你只是有一些语法错误。

您在 number = getValue(romNum.charAt(1) - getValue(romNum.charAt(0));

中缺少结尾 )

此外,在您的大多数 getElementById() 元素中,您的 ID 周围都缺少引号。您需要在 else 块中将变量 ronNum 更改为 romNum

修复这些问题似乎可以让您的某些功能正常工作。您现在只需要处理您的重置按钮功能。希望这会有所帮助。

<html>
<head>
    <title>Roman Numeral Converter</title>
</head>
<body>
<div> 
    <p id="countdown"></p>
    <p id="time"></p>
    <p> Please enter a Roman number (e.g. LIV) to convert to a number: </p>
    <form action="PayslipServlet" method="get">
        <input type="text" name="romannumber" id="rn"> => <span id="result"></span>
        <br>
        <input type="button" value="Convert" onClick="toNumber()"> <input type="button" value="Reset" onclick="empty()">
    </form>
</div>
<script type="text/javascript">

        function sbCountdown() {

            var countdownDate = new Date("February 2, 2020").getTime();

            var now = new Date();
            var rn = now.getTime();

            var daysLeft = countdownDate - rn;

            var days = Math.floor(daysLeft / (1000 * 60 * 60 * 24));

            document.getElementById("countdown").innerHTML = "There are " + days + " days until SUPER BOWL LIV 2020 (February 2, 2020)";

            if(daysLeft < 0) {
                document.getElementById('countdown').innerHTML = "EXPIRED";
            }

            setTimeout(sbCountdown, 1000);
        }

    sbCountdown();


    function updateClock() {

        var now = new Date(), // current date
        months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var dateString = "*** The Current Time is: ";
        var hh = now.getHours();
        var dd = "AM";
        var h = hh;
        if(h >= 12 ) {
            h = hh - 12;
            dd = "PM";
        }
        if( h == 0 ) {
            h = 12;
        }
        time = h + ':' + now.getMinutes() + ':' + now.getSeconds() + " " + dd; 

        // a cleaner way than string concatenation
        date = [now.getDate(), 
            months[now.getMonth()],
            now.getFullYear()].join(' ');

        // set the content of the element with the ID time to the formatted string
         document.getElementById('time').innerHTML = dateString + date + " , " + time;

        // call this function again in 1000ms
        setTimeout(updateClock, 1000);
    }

    updateClock();


    function getValue(s) {

        var num = 0;

        if(s == 'I') { num = 1 }
        else if(s == 'V') { num = 5 }
        else if(s == 'X') { num = 10 }
        else if(s == 'L') { num = 50 }
        else if(s == 'C') { num = 100 }
        else if(s == 'D') { num = 500 }
        else if(s == 'M') { num = 1000 }
        else { document.getElementById('result').innerHTML = "Not a Roman Numeral" }

        return num;
    }

    function toNumber() {

        var total = 0;
        var romNum = document.getElementById('rn').value
        var number;


        while(romNum != "") {

            if(getValue(romNum.charAt(0)) >= getValue(romNum.charAt(1)) || romNum.length == 1) {

                number = getValue(romNum.charAt(0));
                total += number;

                var temp = romNum.slice(1);
                romNum = temp;
            }
            else {

                number = getValue(romNum.charAt(1)) - getValue(romNum.charAt(0));
                total += number;

                var temp = romNum.slice(2);
                romNum = temp;
            }

        }

        document.getElementById('result').innerHTML = total;
    }


</script>

</body>
</html>

这里可能是最简单紧凑的 JavaScript 函数,可将罗马字转换为数字和将数字转换为罗马字,其中还包括验证——例如“LV”是 55,但“VL”不是有效的罗马字数.

function numberToRoman(val,rom){ //returns empty string if invalid number
  rom=rom||''
  if(isNaN(val)||val==0) 
    return rom;
  for(i=0;curval=[1000,900,500,400,100,90,50,40,10,9,5,4,1][i],i<13;i++)
    if(val >= curval)
       return numberToRoman(val-curval,rom+['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'][i])
}

function romanToNumber(txtRom){//returns NaN if invalid string
  txtRom=txtRom.toUpperCase();
  if (!/^M*(CM|CD|(D?C{0,3}))?(XC|XL|(L?X{0,3}))?(IX|IV|(V?I{0,3}))?$/.test(txtRom))
    return NaN;
  var retval=0;
  txtRom.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, function(i) {
    retval += {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1}[i]; 
  });
  return retval;
}
#tblRoman{border-collapse:collapse;font-family:sans-serif;font-size:.8em}
<h3>Roman to Number Conversion</h3>

Enter a Roman Number below, or click on an example button. Then click Convert 
<br><br>
<input type="button" value="example 1" onclick="document.getElementById('romanval').value='LV'">
<input type="button" value="example 2" onclick="document.getElementById('romanval').value='VL'">
<input type="button" value="example 3" onclick="document.getElementById('romanval').value='mmmmmmmcdlxxxiv'">
<input type="button" value="example 4" onclick="document.getElementById('romanval').value='mmmmmmmdclxxxiv'">
<br><br>
<input type="text" size="40" id="romanval">
 <input type="button" onclick="document.getElementById('resultval').innerText
 = romanToNumber(document.getElementById('romanval').value)" value="Convert"> 
<p />
Resulting Decimal Value: <b id="resultval"></b>

<hr>

<h3>Number to Roman Conversion</h3>
<input type="button" value="Generate table upto 2000" onclick="document.getElementById('tblRoman').innerHTML ='</tr>'+[...Array(2000).keys()].map(x => '<td>'+(x+1)+': '+numberToRoman(x+1)+'</td>'+((x+1)%10==0?'</tr><tr>':'')).join('')+'</tr>'">

<table id="tblRoman" border></table>