43 lines
2.3 KiB
Plaintext
43 lines
2.3 KiB
Plaintext
---
|
|
title: '`null`, `undefined` 和未声明变量的区别是什么?'
|
|
subtitle: 您将如何检查这些状态?”
|
|
---
|
|
|
|
**未声明** 当您将一个值分配给以前没有使用 `var`、`let` 或 `const`创建的标识符时,将创建变量。 未声明的变量将在目前范围之外在全球范围内加以界定。 在严格模式下,当你试图赋值到一个未声明的变量时,将会抛出一个 `ReferenceError` 。 未声明的变量是不好的,就像全局变量是不好的一样。 不惜一切代价避免他们! 若要检查它们,将其用法放在一个`try`/`catch`块中。
|
|
|
|
```js
|
|
function foo() {
|
|
x = 1; // Throws a ReferenceError in strict mode
|
|
}
|
|
|
|
foo();
|
|
console.log(x); // 1
|
|
```
|
|
|
|
一个 `undefined` 变量是一个已经声明的变量,但没有赋值。 它是`undefined`类型。 如果一个函数不返回任何值,作为执行它的结果赋值给一个变量,该变量的值也是`undefined`。 若要检查它,请使用严格平等(`===`) 运算符或 `typeof`其结果是`'undefined'` 字符串。 注意,你不应该使用抽象的平等运算符来检查,因为如果值是 `null`,它也会返回 `true`。
|
|
|
|
```js
|
|
var foo;
|
|
console.log(foo); // undefined
|
|
console.log(foo === undefined); // true
|
|
console.log(typeof foo === 'undefined'); // true
|
|
|
|
console.log(foo == null); // true. 错了,不要用这个来检查!
|
|
|
|
function bar() {}
|
|
var baz = bar();
|
|
console.log(baz); // undefined
|
|
```
|
|
|
|
一个 `null` 变量将被明确赋值给 `null` 的值。 它不代表任何价值,与 `undefined` 不同的是,它已被明确赋值。 要检查 `null` 只需使用严格的平等运算符进行比较。 注意,和上面一样,你不应该使用抽象的平等运算符(`==`)来检查,因为如果值是`undefined`,它也会返回`true`。
|
|
|
|
```js
|
|
var foo = null;
|
|
console.log(foo === null); // true
|
|
console.log(typeof foo === 'object'); // true
|
|
|
|
console.log(foo == undefined); // true. Wrong, don't use this to check!
|
|
```
|
|
|
|
作为一个良好的习惯,永远不要让你的变量未被声明或未被赋值。 如果你还不打算使用它们,在声明后明确地将`null`赋值给它们。 如果你在工作流程中使用一些静态分析工具(如 ESLint、TypeScript 编译器),它通常也能检查你是否引用了未声明的变量。
|