JS 中判断空值 undefined 和 null
做项目的时候遇到这个,就顺便把他记录下来啦!当做经验累积……
我做了几个小测试,有带引号的不带引号的。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="jquery-3.4.1.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>小白网页</title>
</head>
<body>
<input type="button" onclick="dangClick1()" value="当1!" style="color: green;" /><br/>
<input type="button" onclick="dangClick2()" value="当1!" style="color: green;" /><br/>
<input type="button" value="当2!" id="test1"/><br/>
<input type="button" value="当3!" id="test2"/>
<script>
//这个方法可以判断,但是会把null值也拦截了,不可取。
function dangClick1(){
var BillNo=undefined;//null
var EntryID=undefined;//null
if(BillNo == undefined && EntryID == undefined){
BillNo=null;
EntryID=0;
alert( "BillNo="+ BillNo +", EntryID="+ EntryID );
}
alert( "BillNo=="+ BillNo +", EntryID=="+ EntryID );
}
//这个方法不可取。
function dangClick2(){
var BillNo=undefined;//null
var EntryID=undefined;//null
if(BillNo == "undefined" && EntryID == "undefined"){
BillNo=null;
EntryID=0;
alert( "BillNo="+ BillNo +", EntryID="+ EntryID );
}
alert( "BillNo=="+ BillNo +", EntryID=="+ EntryID );
}
//这个方法把可以判断,没什么问题,项目里用的是这种。
document.getElementById("test1").onclick=function(){
var BillNo=undefined;
var EntryID=undefined;
if(typeof(BillNo) == undefined && typeof(EntryID) == undefined){
BillNo=null;
EntryID=0;
alert( "BillNo="+ BillNo +", EntryID="+ EntryID );
}
alert( "BillNo=="+ BillNo +", EntryID=="+ EntryID );
}
//这个方法无法判断。
document.getElementById("test2").onclick=function(){
var BillNo=undefined;
var EntryID=undefined;
if(typeof(BillNo) == "undefined" && typeof(EntryID) == "undefined"){
BillNo=null;
EntryID=0;
alert( "BillNo="+ BillNo +", EntryID="+ EntryID );
}
alert( "BillNo=="+ BillNo +", EntryID=="+ EntryID );
}
</script>
</body>
</html>
底层的我暂时还没研究,有人有理解欢迎随时评论、随时指教呀,我不胜荣幸。
null值得判断最重要是把常量值放前头,
if(a==null && "".equal(a)){
a="lalala";
}
总结到这咯!