在 JavaScript 中使用 null 而不是 undefined 的原因是什么? [英] What reason is there to use null instead of undefined in JavaScript?

查看:37
本文介绍了在 JavaScript 中使用 null 而不是 undefined 的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写 JavaScript 很长时间了,我从来没有理由使用 null.似乎 undefined 总是更可取,并且以编程方式服务于相同的目的.使用 null 而不是 undefined 的一些实际原因是什么?

I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?

推荐答案

nullundefined 本质上是两个不同的值,它们表示同一件事.唯一的区别在于您在您的系统中如何使用它们的约定.正如一些人提到的,有些人使用 null 来表示没有对象".有时您可能会得到一个对象,而 undefined 意味着没有预期的对象(或存在错误).我的问题是它完全随意,而且完全没有必要.

null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.

也就是说,有一个主要区别 - 未初始化的变量(包括未传递参数的函数参数等)总是未定义.

That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.

这就是为什么在我的代码中我从不使用 null 除非我无法控制的东西返回 null(例如正则表达式匹配).这样做的美妙之处在于它简化了很多事情.我从不需要检查 x === undefinedx === null.如果你习惯于使用 == 或者只是像 if(x) ... 这样的东西,停止它.

Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined or x === null. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.

!x 对于空字符串,0nullNaN 将评估为真 - 即事物你可能不想要.如果您想编写不糟糕的 javascript,请始终使用三重等于 === 并且永远不要使用 null(改为使用 undefined).它会让您的生活更轻松.

!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

这篇关于在 JavaScript 中使用 null 而不是 undefined 的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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