【问题标题】:How to know what type of variable user enter in JavaScript?如何知道用户在 JavaScript 中输入了什么类型的变量?
【发布时间】:2020-10-03 11:50:16
【问题描述】:

我尝试创建一个函数来接收来自用户的数据,并在字符串的情况下通过连接或在输入的数据为整数时通过获取总和来组合这些数据。 我的主要问题是我不知道我使用的 if 语句中的什么条件来 JavaScript 根据用户输入的数据进行操作。

这是我最后发明的解决此类问题的代码

function GetFullName() {
            var first = document.getElementById('FirstName').value;
            var last = document.getElementById('LastName').value;

            if (first == "string" || last == "string") {               
                document.getElementById('FullName').value = first + " " + last;

            } else {
                var first = parseInt(document.getElementById('FirstName').value);
                var last = parseInt(document.getElementById('LastName').value);

                document.getElementById('FullName').value = first + last;
               
            }
            document.getElementById('FirstName').focus();
        }
<form>
        First Name <input type="text" id="FirstName" />
        Last Name <input type="text" id="LastName" />
        <input type="button" value="submit" onclick="GetFullName()" />
        <input type="reset" value="reset" />
        <br />
        Full Name <input type="text" id="FullName" />
    </form>

【问题讨论】:

  • var first; try { first = JSON.parse(document.getElementById('FirstName').value); } catch (e) { first = document.getElementById('FirstName').value }

标签: javascript function variables var


【解决方案1】:

当你得到一个元素的值时,它总是一个字符串,

您可以通过typeof first检查变量类型

对于您的具体问题,如果您想检查用户是否输入了整数,那么您将不得不使用isNaN

if(isNaN("123")) {

} else {
   //this executes
}

所有的新代码将是:

if (isNaN(first) || isNaN(last)) {
    document.getElementById('FullName').value = first + " " + last;
} else {
    document.getElementById('FullName').value = parseInt(first) + parseInt(last);
}

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多