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