我的 console.log 一直说 NaN 是错误的,而事实并非如此

My console.log keeps saying NaN is false while it isn't

所以我有这段代码,当用户键入一个数字时,它应该在控制台中记录 "this is a valid number",否则它应该记录 "this is not a valid number"。但是我的代码一直在记录 "this is a valid number"。而且我必须使用 isNaN。

请放轻松,我才刚刚开始JavaScript。

这是我的 HTML 代码:

  <!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Postcode</title>


    <script src="postcode.js">
 </script>
</head>

<body>

<form class="form">
  <label for="postcode">Postcode: </label>
  <input type="text" id="postcode">
</form>

</body>

</html>

这是我的 JavaScript 代码:

window.addEventListener("load", init);

  function init() {
    alert("Content loaded");

    var nameInput = document.getElementById('postcode');

    document.querySelector('form.form').addEventListener('submit', function (e) {

      //prevent the normal submission of the form
      e.preventDefault();



        if (nameInput === isNaN || nameInput === "") {
          console.log("this is not a valid number!");}
        else if (nameInput !==  isNaN) {
          console.log("this is a valid number!");}

    });

    }

javascript 中有一个叫做 NaN (Not A Number), then there's a function that checks if something is NaN appropriately called isNaN() 的东西。

您正在检查您的变量是否与 isNaN 函数完全相同,当然不是,因为 nameInput 是一个对象,或者更准确地说是 HTML输入元素。

你想要的可能是获取输入的值,并检查它是否是 "Not A Number",或者只是一个空字符串 (这似乎是一个不必要的检查)

if (isNaN(nameInput.value) || nameInput.value === "") {

使用isNaN(...)检查某物是否不是数字:

isNaN('a'); // true

并且nameInput引用了一个DOM节点,获取值(或innerHTML):

isNaN(nameInput.value)

以及您的完整代码:

window.addEventListener("load", init);

function init() {
    var nameInput = document.getElementById('postcode');
    document.querySelector('.form').addEventListener('submit', function (e) {
        e.preventDefault();
        if (!nameInput.value || isNaN(nameInput.value)) {
            console.log("this is not a valid number!");}
        else {
            console.log("this is a valid number!");}
        }
    });
}

isNaN 是一个函数。如果你做 nameInput === isNaN,你检查 nameInput 是否指向函数 isNaN。 你想要做的是调用函数:isNaN(nameInput).

nameInput 也是 HTML DOM Element。您首先必须从中获取值:nameInput.value

就这样:

if (isNaN(nameInput.value)) {
    console.log("this is not a valid number!");}
else {
    console.log("this is a valid number!");
}