undefined: 未定义 var message; //定义了,但是没有赋值 console.log(message); //undefined 这个未定义不是说一个变量没有var xx的意思,只
undefined: 未定义
var message; //定义了,但是没有赋值
console.log(message); //undefined
这个未定义不是说一个变量没有var xx的意思,只是说定义了但是没有赋值, 如果压根就没有var xx将会引发异常:
console.log(xx) // xx is not defind
但是undefined和操作符进行操作的时候会是什么样呢:
console.log(undefined+1); //NaN 表示非数值类型 not a number
console.log(undefined+"1"); //undefined1 此时会把undefined当成一个完整的字符串
console.log(true+undefined); //NaN
console.log(null+undefined); //NaN
也就是说undefined与除string类型以外的其他类型进行数学操作都会返回NaN,因为js里的var是根据结果来确认类型的,所以js编译器会认为不知道是一个什么类型与你已知的数进行操作,所以返回是的是一个NaN (not a Number)
null: 空
null是object对象,感觉最容易混淆的就是undefined和null,undefined继承于null,所以有的时候一直觉得js这种设计压根就是在增加你的难度,所以如果有这个可能的话真希望这俩合二为一,
console.log(null==undefined); //true
console.log(null===undefined) //false
console.log(typeof null); //object
console.log(typeof undefined);// undefined
但是null在操作的时候基本都用不到,一般是在操作对象的时候会用到null,不过他在进行数学操作的时候是什么样呢?
console.log(null+1)//1
console.log(null*1)//0
console.log(null*"1")//0
console.log(null*"dsfadad")//NaN(在数学里面0乘以任何数都是0, 但是任何数应该是数值,乘以一个字符串肯定无法计算,所以js就用NaN来表示了)
console.log(null*"1")//0
console.log(null*"-1")//-0
console.log("1"+null)//1null 当和字符串相加则变成字符串了,
感觉这玩意确实有点坑爹
所以我的理解是null就是0
实际应用:
null判断获取到的对象是否为null
<div id="lga">sssssssssssss</div>
if($("#lga")!=null){
console.log("存在");
}
undefined一般判断变量
var message;
ifi(message==undefined){
console.log("存在");
}
要分清null和undefined的区别,请看名人博客
http://www.ruanyifeng.com/blog/2014/03/undefined-vs-null.html