undefined和null都表示“无,没有”,都是js中的基本类型
如果把变量a分别赋值undefined和null,这两种写法基本等价
如果应用在if语句中,则两者都会被自动转成false
var a = undefined
var b = null
if (!a) {
console.log('undefined is false');
}
if (!b) {
console.log('null is false');
}
undefined is false
null is false
如果两者进行运算,也会直接报告相等
undefined == null
true
你可以定义一个值为null,证明它是空的,但如果你定义它是undefined(未被定义的),逻辑上不合理,尽管你可以这样做
null:
(1)作为函数的参数,来表示该函数的参数不是对象
(2)作为对象原型链的终点
Object.getPrototypeOf(Object.prototype)
// null
undefined:
(1)变量被声明了,但没有赋值时,就等于undefined。
(2) 调用函数时,应该提供的参数没有提供,该参数等于undefined。
(3)对象没有赋值的属性,该属性的值为undefined。
(4)函数没有返回值时,默认返回undefined。
var a = Number(undefined)
console.log('a=',a);
var b = Number(null)
console.log('b=',b);
运行结果为
a = NaN
b = 0
证明undefined 转化为数字类型为NaN(Not-a-Number 非数字值)
而null转化为数字类型,结果为0
定义:JavaScript中,NaN是一个特殊的数字值,是 Not-a-Number 的缩写,表示不是一个合法的数字
如果用typeof查看其数据类型
console.log(typeof(NaN))
结果为
Number
NaN的产生
①Number()无法解析的数字类型
Number('abc') // NaN
Number(undefined) // NaN
②Math计算失败的结果
Math.sqrt(-2) // 负数的平方根
Math.log(-1) // 负数的自然对数(底数为e)
Math.acos(2) // 超过1的反余弦值
计算结果均为NaN
③参与运算的任意一个成员为NaN
NaN + 1 // NaN
10 / NaN // NaN
特殊性
*NaN是唯一一个和自身不相等的值:
NaN === NaN // false
相关函数
isNaN() 用于判断一个数值是不是一个非数字(不是专门用来判断NaN)
isNaN(NaN) // true
isNaN(10) // false
isNaN('abc') // true
结果表明,如果一个值是例如字符串类型,isNaN返回的结果也是true,所以不能用来判断NaN
如果你想判断一个数值是NaN,可以采用isNaN()和typeof结合的方式
function isValueNaN(value) {
return typeof value === 'number' && isNaN(value)
}
文章参考:
(4条消息) JS中的NaN_码飞_CC的博客-CSDN博客_js nan
undefined与null的区别 - 阮一峰的网络日志 (ruanyifeng.com)
持续更新中......