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

查看:137
本文介绍了什么原因在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?

推荐答案

Null和undefined本质上是两个不同的值,意思是相同的。唯一的区别在于约定如何在 系统中使用它们。正如一些人所提到的,有些人使用null表示无对象,你有时可能会获得一个对象,而未定义意味着没有预期的对象(或者有错误)。我的问题是完全随意,完全没必要。

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 === undefined || x === null。如果你习惯使用==或简单的东西,如if(x)....停下来。 !x 将为空字符串,0,null,NaN评估为true - 即您可能不想要的东西。如果你想编写不太糟糕的javascript,请始终使用triple equals ===并且永远不要使用null(使用undefined代替)。它会让你的生活变得更轻松。

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 simiplifies things a lot. I never have to check if x === undefined || x === null. And if you're in the habit of using == or simply stuff like if(x) ... . Stop it. !x will evaluate to true for an empty string, 0, null, NaN - ie 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天全站免登陆