1. undefined的情况
未赋值的变量或读取对象没有的属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var num;
var student = {
name:"Sam",
age:13
};
console.log(num);//未赋值
console.log(student.interest);//没有的属性
</script>
</body>
</html>
2. null的情况
给的值无效,或者说就是给的null
student.interest = null;
console.log(student.interest);
3、检查变量或属性是否为null 或 undefined
他俩在逻辑上,划给布尔值boolean-----false
【案例】----验证表单元素是否为空
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="username" id="userName">
<!-- 添加事件 -->
<input type="button" value="验证" id="subBut" onclick = "test()">
<script>
var textObj = document.getElementById("userName");
// 验证函数
function test(){
var textValue = textObj.value;
if(!textValue){
console.log("表单项不能为空!");
}else{
console.log("已经有值");
}
}
</script>
</body>
</html>