我何时使用null初始化JavaScript中的变量? [英] When do I initialize variables in JavaScript with null or not at all?

查看:79
本文介绍了我何时使用null初始化JavaScript中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了声明变量并设置为undefined和null的不同代码示例。如:

I have seen different code examples with variables declared and set to undefined and null. Such as:

var a; // undefined - unintentional value, object of type 'undefined'
var b = null; // null - deliberate non-value, object of type 'object'

如果要遵循这些代码声明为a或b分配一个值,使用一种声明而不是另一种声明的原因是什么?

If the code to follow these declarations assigns a value to a or to b, what is the reason for using one type of declaration over another?

推荐答案

第一个示例没有为变量赋值,因此它隐式引用 undefined 值(参见 10.5规范中的细节)。它通常在声明变量供以后使用时使用。在必要之前,无需明确地为它们分配任何内容。

The first example doesn't assign anything to the variable, so it implicitly refers to the undefined value (see 10.5 in the spec for the details). It is commonly used when declaring variables for later use. There is no need to explicitly assign anything to them before necessary.

第二个示例是显式分配的 null (其中实际上是 null 类型,但由于JavaScript规范的怪癖,声称具有类型object)。它通常用于清除已存储在现有变量中的值。清除值时,可以看到使用 null 更加健壮,因为可以覆盖 undefined ,并且分配 undefined 的情况会导致意外行为。

The second example is explicitly assigned null (which is actually of type null, but due to a quirk of the JavaScript specification, claims to have type "object"). It is commonly used to clear a value already stored in an existing variable. It could be seen as more robust to use null when clearing the value since it is possible to overwrite undefined, and in that situation assiging undefined would result in unexpected behaviour.

顺便说一下, null 是使用更健壮的类型检查形式的一个很好的理由:

As an aside, that quirk of null is a good reason to use a more robust form of type checking:

Object.prototype.toString.call(null); // Returns "[object Null]"

这篇关于我何时使用null初始化JavaScript中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆