📜  空和未定义之间的区别

📅  最后修改于: 2021-01-11 12:19:39             🧑  作者: Mango

空和未定义之间的区别

空值

Null用于表示故意缺少值。它代表一个变量,其值是不确定的。它仅接受一个值,该值为null。 Null关键字用于在TypeScript中定义Null类型,但是它没有用,因为我们只能为其分配一个null值。

//Variable declared and assigned to null
var a = null; 
console.log( a );   //output: null
console.log( typeof(a) );   //output: object

输出:

未定义

它表示TypeScript和JavaScript中的未初始化变量。它只有一个未定义的值。 undefined关键字在TypeScript中定义了undefined类型,但是它没有用,因为我们只能为其分配一个undefined值。

//Variable declaration without assigning any value to it
var a;      
console.log(a);  //undefined
console.log(typeof(a));  //undefined
console.log(undeclaredVar);  //Uncaught ReferenceError: undeclaredVar is not defined

输出:

空值与未定义

Null和Undefined之间的重要区别是:

SN Null Undefined
1. It is an assignment value. It can be assigned to a variable which indicates that a variable does not point any object. It is not an assignment value. It means a variable has been declared but has not yet been assigned a value.
2. It is an object. It is a type itself.
3. The null value is a primitive value which represents the null, empty, or non-existent reference. The undefined value is a primitive value, which is used when a variable has not been assigned a value.
4. Null indicates the absence of a value for a variable. Undefined indicates the absence of the variable itself.
5. Null is converted to zero (0) while performing primitive operations. Undefined is converted to NaN while performing primitive operations.