为什么我的代码片段在条件不为真时仍在执行?

Why my code snippet in the condition still executing while the condition is not true?

提问人:Rohaib Razzaq 提问时间:11/7/2023 更新时间:11/7/2023 访问量:48

问:

          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 ");
          }

当我输入数值时,我预计不会发出警报,但它仍然在条件中显示警报消息。

JavaScript HTML 输入

评论

4赞 Pointy 11/7/2023
any 的属性始终是一个字符串。.value<input>
0赞 Krokodil 11/7/2023
显然,条件真,否则将不会执行警报语句 - 计算机不会犯错误。

答:

0赞 J.Porter 11/7/2023 #1

Input 的值始终为字符串。

因此,您可以执行以下操作。

let Year =document.getElementById('year').value;
let Month =document.getElementById('month').value;
let date =document.getElementById("day").value;
if(isNaN(Year+Month+date) ){
  alert("Invalid Date ");  
 
}

你需要更多的验证,比如......但我的代码现在和你的代码一样足够了。date > 0

我想我的答案可以帮助你。

评论

1赞 Pointy 11/7/2023
这里的问题是表达式将使用字符串值进行计算,这意味着数值字符串将被连接,而不是相加。Year+Month+date
0赞 J.Porter 11/7/2023
我知道。 .你认为勾选“20231112”与勾选 3 String each 不同吗?例如,如果 是,则总和 是,检查结果也是 false。'2023' + '11' + '12' = '20231112'Month"d"2023d12
0赞 Krokodil 11/7/2023
然后你需要使用,因为这更明确isNan(Number(...))
0赞 J.Porter 11/7/2023
@Krokodil,自己试试吧。 是和是.isNan("2")falseisNan("d")true
0赞 J.Porter 11/7/2023
我想我写的答案是正确的,但我的答案是现在。:(-1