为什么每次都给我返回字符串?

4

我从输入标签中获取输入,但无论我在输入框中写什么,它都会被识别为字符串值,因此我无法使用条件语句。

第二个问题是,如果我在第一个输入框中输入“ddd”,在第二个输入框中输入“111”,然后按下按钮,控制台会显示NaN。我想要弹出警告而不是这个结果。我该如何纠正这些问题?

function addFunc() {
  var x = document.getElementById("num1").value;
  var y = document.getElementById("num2").value;

  if (typeof x == 'string' || typeof y == 'string') {
    var result = parseInt(x) + parseInt(y);
    console.log(result);
  } else {
    alert("Wrong Entry!");
  }
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>


因为“DDDD”是一个字符串。检查它是否不是一个数字。https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isNaN - epascarello
1
document.getElementById("num1").value将始终返回字符串。无论您在输入框中键入什么内容,它始终是文本。 为了避免NaN,您必须使用isNaN()函数进行NaN检查。 - Alex K
1个回答

5
字段的值始终为字符串。尝试使用isNaN()函数来确定十进制数是否被正确地解析:

function addFunc() {
    var x = parseInt(document.getElementById("num1").value);
    var y = parseInt(document.getElementById("num2").value);

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>

或者,如果您想消除所有不良输入(例如1e将无效),请尝试在字符串值之前使用+符号将其转换为数字。如果字符串无法转换,则会返回NaN

function addFunc() {
    var x = +document.getElementById("num1").value;
    var y = +document.getElementById("num2").value;

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>


你能否输入1e作为第一个输入,11作为第二个输入并观察结果? - NoWeDoR
parseInt() 将尝试在解析之前删除所有非整数字符。这不是您想要的吗? - Blue

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接