空检查正在产生问题

  • 本文关键字:问题 javascript null
  • 更新时间 :
  • 英文 :

let age = prompt('What is your name?');
if(age  != null){
document.write(`Your name is ${age}`) 
}else{
document.write("You didn't enter your age");
}

空检查不起作用,即使我把它留空,它也会显示:你的名字是

但当我写这篇文章时-

let age = prompt('What is your name?');
if(age == null){
document.write(`Your name is ${age}`) 
}else{
document.write("You didn't enter your age");
}

它总是显示"你没有输入你的年龄">

因为当您不输入内容时,age不包含null,而是一个空字符串(长度为0的字符串(。您可以通过以下方式确认:

let age = prompt('What is your name?');
console.log(age); // prints ''
console.log(age.length); // prints 0
if(age  != null){
document.write(`Your name is ${age}`) 
}else{
document.write("You didn't enter your age");
}

事实上,你只需要做:

let age = prompt('What is your name?');
if(age){
document.write(`Your name is ${age}`) 
}else{
document.write("You didn't enter your age");
}

相关内容

  • 没有找到相关文章

最新更新