将字符串转换为秒数

Converting string to number of seconds

本文关键字:转换 字符串      更新时间:2023-09-26

我正在尝试创建一个简单的程序,该程序将用户提供的小时数转换为秒数,并要求用户重新输入小时数,如果他提供一个字符串。当我输入非正数时,它工作正常,但如果输入字符串值,则不会显示任何消息。这是代码:

        function convertToSeconds () {
            var d = prompt("Enter any hour between 0-24","4");
            if ( d<0 ){
                alert("Please enter a number greater than zero");
                convertToSeconds();
            }
            else if( typeof d == String ) {
                /*Problem seems to be here*/
                alert(d + " is not a valid number");
                convertToSeconds();
            }
            else {
            var seconds = 3600*parseFloat(d);
            document.write(seconds);
            }
        };
        convertToSeconds();

prompt 方法返回字符串。您需要确定字符串是否可以转换为 0 到 24 之间的正整数,因此:

var d = prompt('Enter any hour between 0-24');
if ( /^(1?[0-9]|2[0-4])$/.test(d) ) {
  alert('looks good');
} else {
  alert('don''t like that');
}

或者你可以做这样的事情:

var d = Number(prompt('Enter any hour between 0-24'));
if (d == parseInt(d) && d > -1 && d < 25 {
  // ok
}
  // not ok
}

只是你的代码有问题。 typeof "any string" = "string" 不是String,默认情况下,JS也将字符串格式的数字强制为数字,因此我建议在数字之前检查字符串。

function convertToSeconds () {
var d = prompt("Enter any hour between 0-24","4");
    if ( d<0 ){
        alert("Please enter a number greater than zero");
        convertToSeconds();
    }        
    else if( isNaN(d) ) {
        /*Problem seems to be here*/
        alert(d + "is not a valid number");
        convertToSeconds();
    }
    else {
    var seconds = 3600*parseFloat(d);
    document.write(seconds);
    }
};
convertToSeconds();