JavaScript 中何时使用 null 或 undefined?

发布于 2024-11-16 15:11:24 字数 328 浏览 1 评论 0原文

我对 JavaScript 何时返回 null 或 undefined 感到困惑。此外,不同的浏览器似乎以不同的方式返回这些内容。

我正在寻找一些 null/undefined 以及返回它们的浏览器的示例。

虽然我现在对 undefined 方面很清楚,但对于 null 仍然不是 100% 清楚。它类似于空白值吗?

例如,您有一个没有设置任何值的文本框。现在,当您尝试访问它的值时,它会是 null 还是 undefined ,它们是否相似?

I am confused as to when JavaScript returns null or undefined. Also different browsers seem to be returning these differently.

I am seeking some examples of null/undefined with the browsers that return them.

While I am now clear on the undefined aspect, I am still not 100% clear on null. Is it similar to a blank value?

E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null or undefined and are they similar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小嗲 2024-11-23 15:11:24

我发现其中一些答案模糊且复杂,我发现确定这些问题的最佳方法就是打开控制台并亲自测试。

var x;

x == null            // true
x == undefined       // true
x === null           // false
x === undefined      // true

var y = null;

y == null            // true
y == undefined       // true
y === null           // true
y === undefined      // false

typeof x             // 'undefined'
typeof y             // 'object'

var z = {abc: null};

z.abc == null        // true
z.abc == undefined   // true
z.abc === null       // true
z.abc === undefined  // false

z.xyz == null        // true
z.xyz == undefined   // true
z.xyz === null       // false
z.xyz === undefined  // true

null = 1;            // throws error: invalid left hand assignment
undefined = 1;       // works fine: this can cause some problems

所以这绝对是 JavaScript 更微妙的细微差别之一。正如您所看到的,您可以覆盖 undefined 的值,使其与 null 相比有些不可靠。据我所知,使用 == 运算符,您可以可靠地互换使用 nullundefined 。但是,由于 null 无法重新定义的优点,我可能会在使用 == 时使用它。

例如,如果 variable 等于 nullundefined,则 variable != null 将始终返回 false,而如果 variable 等于 nullundefined,除非 undefined< /code> 已预先重新分配。

如果您需要确保某个值实际上是 ,您可以可靠地使用 === 运算符来区分 undefinednull >未定义(而不是null)。

根据 ECMAScript 5 规范:

  • NullUndefined 都是六种内置类型中的两种。

4.3.9 未定义值

未给变量赋值时使用的原始值

4.3.11 null 值

表示故意不存在任何对象值的原始值

I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.

var x;

x == null            // true
x == undefined       // true
x === null           // false
x === undefined      // true

var y = null;

y == null            // true
y == undefined       // true
y === null           // true
y === undefined      // false

typeof x             // 'undefined'
typeof y             // 'object'

var z = {abc: null};

z.abc == null        // true
z.abc == undefined   // true
z.abc === null       // true
z.abc === undefined  // false

z.xyz == null        // true
z.xyz == undefined   // true
z.xyz === null       // false
z.xyz === undefined  // true

null = 1;            // throws error: invalid left hand assignment
undefined = 1;       // works fine: this can cause some problems

So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.

For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.

You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).

According to the ECMAScript 5 spec:

  • Both Null and Undefined are two of the six built in types.

4.3.9 undefined value

primitive value used when a variable has not been assigned a value

4.3.11 null value

primitive value that represents the intentional absence of any object value

余罪 2024-11-23 15:11:24

DOM 方法 getElementById()nextSibling()childNodes[n]parentNode() 等当调用不返回节点对象时返回null(已定义但没有值)。

属性已定义,但它引用的对象不存在。

这是您可能不想想要测试相等性的少数情况之一 -

if(x!==undefined) 对于 null 值将为 true,

if (x!= undefined)(仅)对于非 undefinednull 的值将为 true。

The DOM methods getElementById(), nextSibling(), childNodes[n], parentNode() and so on return null (defined but having no value) when the call does not return a node object.

The property is defined, but the object it refers to does not exist.

This is one of the few times you may not want to test for equality-

if(x!==undefined) will be true for a null value

but if(x!= undefined) will be true (only) for values that are not either undefined or null.

初见你 2024-11-23 15:11:24

对于各种情况,您都会遇到未定义的情况:

您使用 var 声明一个变量,但从未设置它。

var foo; 
alert(foo); //undefined.

您尝试访问从未设置过的对象上的属性。

var foo = {};
alert(foo.bar); //undefined

您尝试访问从未提供过的参数。

function myFunction (foo) {
  alert(foo); //undefined.
}

正如 cwolves 在另一个答案的评论中指出的那样,函数不返回值。

function myFunction () {
}
alert(myFunction());//undefined

通常必须有意在变量或属性上设置 null(有关未设置 null 的情况,请参阅注释)。此外,null 的类型为object,undefined 的类型为undefined

我还应该注意到 null 在 JSON 中是有效的,但 undefined 不是:

JSON.parse(undefined); //syntax error
JSON.parse(null); //null

You get undefined for the various scenarios:

You declare a variable with var but never set it.

var foo; 
alert(foo); //undefined.

You attempt to access a property on an object you've never set.

var foo = {};
alert(foo.bar); //undefined

You attempt to access an argument that was never provided.

function myFunction (foo) {
  alert(foo); //undefined.
}

As cwolves pointed out in a comment on another answer, functions that don't return a value.

function myFunction () {
}
alert(myFunction());//undefined

A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.

I should also note that null is valid in JSON but undefined is not:

JSON.parse(undefined); //syntax error
JSON.parse(null); //null
淡忘如思 2024-11-23 15:11:24

我可能遗漏了一些东西,但是据我所知,你只得到undefined

更新:好吧,我错过了很多,试图完成:

你得到< code>undefined...

... 当您尝试访问不存在的对象的属性时:

var a = {}
a.foo // undefined

... 当您声明了变量但未初始化它时:

var a;
// a is undefined

... 当您访问参数时没有传递任何值:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

...当函数没有返回值时:

function foo() {};
var a = foo(); // a is undefined

可能是某些内置函数在出现某些错误时返回 null,但如果是这样,则会记录下来。 null 是 JavaScript 中的具体值,而 undefined 则不是。


通常您不需要区分它们。根据变量的可能值,使用 if(variable) 来测试某个值是否已设置就足够了(nullundefined 计算结果为 false)。

此外,不同的浏览器似乎会以不同的方式返回这些内容。

请举一个具体的例子。

I might be missing something, but afaik, you get undefined only

Update: Ok, I missed a lot, trying to complete:

You get undefined...

... when you try to access properties of an object that don't exist:

var a = {}
a.foo // undefined

... when you have declared a variable but not initialized it:

var a;
// a is undefined

... when you access a parameter for which no value was passed:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

... when a function does not return a value:

function foo() {};
var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

Also different browsers seem to be returning these differently.

Please give a concrete example.

三月梨花 2024-11-23 15:11:24

关于这个主题,规范(ecma-262)非常清楚,

我发现它非常有用且简单,因此我分享它:
- 在这里您将找到相等算法
- 在这里你会发现严格相等算法

我碰到了它从 mozilla 开发者网站的相同性部分阅读“抽象平等、严格平等和相同价值”。

我希望你觉得它有用。

Regarding this topic the specification (ecma-262) is quite clear

I found it really useful and straightforward, so that I share it:
- Here you will find Equality algorithm
- Here you will find Strict equality algorithm

I bumped into it reading "Abstract equality, strict equality, and same value" from mozilla developer site, section sameness.

I hope you find it useful.

初见终念 2024-11-23 15:11:24

当一个属性没有定义时,它就是未定义的。
null 是一个对象。它的类型为空。 undefined 不是一个对象,它的类型是未定义的。

这是一篇很好的文章,解释了差异并给出了一些例子。

null 与 undefined

A property, when it has no definition, is undefined.
null is an object. It's type is null. undefined is not an object, its type is undefined.

This is a good article explaining the difference and also giving some examples.

null vs undefined

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文