undefined、null和NaN

在原始类型中有 3 种特殊的值——undefinednullNaN,它们具有一定的相似性,但又各有区别,接下来将分别进行介绍。

undefined

undefined 即缺少初始值,它表示该变量应该有一个值,但是没有为其赋值。在以下情况下,将产生 undefined 值。

  • 变量声明后没有赋值,该变量值为 undefined

  • 在调用函数时,没有提供参数值,因此参数值为 undefined

  • 没有给对象的某个属性赋值,因此该属性的值为 undefined

  • 如果函数没有返回值,则默认返回 undefined

例如,以下代码首先声明一个名为 test 的函数,它拥有一个可选参数 para。接着,声明一个变量 a,但在没有赋值的情况下输出 a 的值,并调用 test() 函数,因为没有传入 para 参数,所以函数体将会输出 para 参数的值。最终输出结果均为 undefined

function test(para?:any){
    console.log(para);
}

let a:number;
console.log(a); //输出undefined
test();         //输出undefined

null

null 即无值,它表示此处不应该有值。null 通常用于引用类型而非原始类型,变量不会自动生成 null 值,需要在代码中明确指定为 null,示例代码如下。

let a: number = null; // Type 'null' is not assignable to type 'number'.
let b: string = null; // Type 'null' is not assignable to type 'string'.
let c: boolean = null; // Type 'null' is not assignable to type 'boolean'.

nullundefined 都可表示无值:null 通常表示预期中的无值,这是一种正常状态;undefined 通常表示非预期产生的无值,这是一种异常状态。

NaN

NaN 即 Not a Number,表示这个值虽属于数值类型,但不是一个正确的数字。

NaN 通常是在将其他类型的值转为数值类型时产生的;后续将详细介绍。例如,以下代码尝试通过 parseInt() 函数将字符串 abc 转换为整数,但 abc 明显不是数字,因此转换成的数字值为 NaN,表示它不是一个正确的数字。

let a = parseInt("abc");
console.log(a); //输出NaN