You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何条件不成立时条件块代码仍执行?输入数值仍触发无效日期提示

问题:输入数值型内容仍触发"Invalid Date"弹窗的原因

我输入了数值型内容,原本预期不会触发弹窗,但代码中的‘Invalid Date’提示框仍会显示,想请教为何条件不成立时该代码片段仍会执行?

代码片段:

let Year = document.getElementById('year').value;
let Month = document.getElementById('month').value;
let date = document.getElementById("day").value;

if(typeof Year !== "number" || typeof Month !== "number" || typeof date !== "number"){
  alert("Invalid Date ");
}

原因分析

HTML输入框的value属性永远返回字符串类型,哪怕你输入的是纯数字。所以你用typeof检测变量类型时,Year、Month、date这三个变量的类型都是string,导致typeof ... !== "number"的条件始终为真,弹窗必然触发。

解决方法

需要先把输入的字符串转换为数字类型,再做判断:

  1. 使用parseInt()转换(适用于整数日期):
let Year = parseInt(document.getElementById('year').value);
let Month = parseInt(document.getElementById('month').value);
let date = parseInt(document.getElementById("day").value);

// 同时判断转换是否成功(输入非数字时会返回NaN)
if(isNaN(Year) || isNaN(Month) || isNaN(date)){
  alert("Invalid Date");
}
  1. 或者使用Number()函数转换:
let Year = Number(document.getElementById('year').value);
let Month = Number(document.getElementById('month').value);
let date = Number(document.getElementById("day").value);

if(isNaN(Year) || isNaN(Month) || isNaN(date)){
  alert("Invalid Date");
}

内容的提问来源于stack exchange,提问作者Rohaib Razzaq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 01:42:11