JavaScript 中有 8 种 数据类型。它们是
| 数据类型 | 描述 |
|---|---|
字符串 |
表示文本数据 |
Number |
一个整数或一个浮点数 |
BigInt |
任意精度的整数 |
布尔型 |
两个值中的任何一个:true 或 false |
对象 |
键值对的数据集合 |
Symbol |
一种实例唯一且不可变的数据类型 |
undefined |
一种变量未初始化的数据类型 |
null |
表示空值的特殊关键字 |
undefined 和 null 是我们将在本教程中讨论的两种数据类型。
JavaScript undefined
如果一个变量已声明但未赋值,则该变量的值将为 undefined。例如:
let name;
console.log(name); // undefined
也可以显式地将 undefined 赋值给一个变量。例如:
let name = "Felix";
// assigning undefined to the name variable
name = undefined
console.log(name); // returns undefined
注意: 通常,null 用于将'未知'或'空'值赋给变量。因此,您可以将 null 赋给一个变量。
JavaScript null
在 JavaScript 中,null 是一个特殊值,表示空或未知值。例如:
let number = null;
上面的代码表明 number 变量目前是空的,稍后可能会有值。
注意:null 不等于 NULL 或 Null。
False Values
在 JavaScript 中,undefined 和 null 被视为 false 值。例如:
if(null || undefined ) {
console.log('null is true');
} else {
console.log('null is false');
}
输出
null is false
当 undefined 或 null 与 Boolean() 函数一起使用时,它们会被转换为 false。例如:
let result;
result = Boolean(undefined);
console.log(result); // false
result = Boolean(null);
console.log(result); // false
JavaScript typeof: null and undefined
在 JavaScript 中,null 被视为一个对象。您可以使用 typeof 运算符来检查这一点。typeof 运算符用于确定变量和值的类型。例如:
const a = null;
console.log(typeof a); // object
当 typeof 运算符用于确定 undefined 值时,它会返回 undefined。例如:
let a;
console.log(typeof a); // undefined
JavaScript Default Values: null and undefined
在访问此部分之前,请务必查看 JavaScript 默认参数教程。
在 JavaScript 中,当您将 undefined 传递给接受默认值的函数参数时,undefined 会被忽略,并使用默认值。例如:
function test(x = 1) {
console.log(x);
}
// passing undefined
// takes default value 1
test(undefined); // 1
但是,当您将 null 传递给默认参数函数时,该函数会将 null 作为值。例如:
function test(x = 1) {
console.log(x);
}
// passing undefined
// takes null
test(null); // null
比较 null 和 undefined
当使用等于运算符 == 比较 null 和 undefined 时,它们被视为相等。例如:
console.log(null == undefined); // true
在 JavaScript 中,== 通过执行 类型转换来比较值。null 和 undefined 都返回 false。因此,null 和 undefined 被视为相等。
但是,当使用严格等于运算符 === 比较 null 和 undefined 时,结果为 false。例如:
console.log(null === undefined); // false