何时检查未定义以及何时检查 null

发布于 2024-10-13 04:29:12 字数 1324 浏览 2 评论 0原文

[赏金编辑]

我正在寻找一个很好的解释,当你应该设置/使用nullundefined以及你需要在哪里检查它。基本上这两者的常见做法是什么,真的可以在通用的可维护代码中单独对待它们吗?

我什么时候可以安全地检查 === null、安全地检查 === undefined 以及什么时候需要使用 == null 检查两者code>

什么时候应该使用关键字 undefined 以及什么时候应该使用关键字 null

我有各种格式为

if (someObj == null)< 的检查/code> 或 if (someObj != null) 用于检查 null 和 undefined。我想将所有这些更改为 === undefined=== null 但我不确定如何保证它永远只是其中之一两个但不是两者。

应该在哪里使用 null 检查以及在哪里使用 undefined 检查

具体示例:

var List = []; // ordered list contains data at odd indexes.

var getObject = function(id) {
    for (var i = 0; i < List.length; i++) {
        if (List[i] == null) continue;
        if (id === List[i].getId()) {
            return List[i];
        }
    }
    return null;
}

var deleteObject = function(id) {
    var index = getIndex(id) // pretty obvouis function
    // List[index] = null; // should I set it to null?
    delete List[index]; // should I set it to undefined?
}

这只是我可以同时使用 null 的一个示例code> 或 undefined,我不知道哪个是正确的。

是否存在因别无选择而必须同时检查 nullundefined 的情况?

[Bounty Edit]

I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?

When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null

When should you use the keyword undefined and when should one use the keyword null

I have various checks in the format of

if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.

Where should you use checks for null and where should you use checks for undefined

A concrete example:

var List = []; // ordered list contains data at odd indexes.

var getObject = function(id) {
    for (var i = 0; i < List.length; i++) {
        if (List[i] == null) continue;
        if (id === List[i].getId()) {
            return List[i];
        }
    }
    return null;
}

var deleteObject = function(id) {
    var index = getIndex(id) // pretty obvouis function
    // List[index] = null; // should I set it to null?
    delete List[index]; // should I set it to undefined?
}

This is just one example of where I can use both null or undefined and I don't know which is correct.

Are there any cases where you must check for both null and undefined because you have no choice?

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

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

发布评论

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

评论(9

等往事风中吹 2024-10-20 04:29:12

函数隐式返回未定义。数组中未定义的键是未定义。对象中未定义的属性是未定义

function foo () {

};

var bar = [];
var baz = {};

//foo() === undefined && bar[100] === undefined && baz.something === undefined

如果未找到任何元素,document.getElementById 将返回 null

var el = document.getElementById("foo");

// el === null || el instanceof HTMLElement

您永远不必检查 undefinednull(除非您从可能返回 null 的源和可能返回 undefined 的源聚合数据)。

我建议您避免 null;使用未定义

Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.

function foo () {

};

var bar = [];
var baz = {};

//foo() === undefined && bar[100] === undefined && baz.something === undefined

document.getElementById returns null if no elements are found.

var el = document.getElementById("foo");

// el === null || el instanceof HTMLElement

You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).

I recommend you avoid null; use undefined.

段念尘 2024-10-20 04:29:12

某些 DOM 方法返回 null。当您尝试访问对象的所有尚未设置的属性时,它们都会返回 undefined,包括 Array 的属性。没有 return 语句的函数隐式返回 undefined

我建议确保您确切地知道您正在测试的变量或属性可能有哪些值,并明确且有信心地测试这些值。要测试 null,请使用 foo === null。为了测试 undefined,我建议在大多数情况下使用 typeof foo == "undefined",因为 undefined (与 null< /code>) 不是保留字,而是全局对象的一个​​简单属性,可以更改,而且出于我最近在这里写的其他原因:变量===未定义与typeof变量===“未定义”

Some DOM methods return null. All properties of an object that have not been set return undefined when you attempt to access them, including properties of an Array. A function with no return statement implicitly returns undefined.

I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use foo === null. For testing for undefined, I would recommend using typeof foo == "undefined" in most situations, because undefined (unlike null) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"

原野 2024-10-20 04:29:12

nullundefined 之间的区别在于 null 本身就是一个值,必须进行赋值。这不是默认值。未分配任何值的全新变量是未定义

var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.

The difference between null and undefined is that null is itself a value and has to be assigned. It's not the default. A brand new variable with no value assigned to it is undefined.

var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.
你是我的挚爱i 2024-10-20 04:29:12

我认为有趣的是,当 Windows 第一次编写时,它并没有对无效/NULL 指针进行大量检查。毕竟,没有程序员会愚蠢到在需要有效字符串的地方传递 NULL。测试 NULL 只会使代码变得更大、更慢。

结果是,很多阿联酋都是因为客户端程序的错误而导致的,但所有的热度都归咎于微软。从那时起,Microsoft 更改了 Windows,几乎检查每个参数是否为 NULL。

我认为教训是,除非你真的确定一个论点总是有效的,否则可能值得验证它是否有效。当然,Windows是很多程序员都用的,而你的函数可能只有你自己用。因此,这肯定会影响无效论证的可能性。

在 C 和 C++ 等语言中,您可以使用 ASSERT,我在使用这些语言时一直使用它们。这些陈述验证了您从未预料到会发生的某些情况。在调试过程中,你可以测试一下,事实上,它们从来没有这样做过。然后,当您进行发布构建时,这些语句不会包含在编译的代码中。从某些方面来说,这对我来说似乎是两全其美。

I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.

The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.

I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.

In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.

贪恋 2024-10-20 04:29:12

如果您调用一个没有显式返回的函数,那么它会隐式返回未定义。因此,如果我有一个函数需要说它完成了它的任务并且没有任何结果,例如当您通常期望会有一些东西(例如数据库调用)时 XMLHTTPRequest 没有返回任何内容,那么我会显式返回

If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.

无可置疑 2024-10-20 04:29:12

使用 !== 时,Undefined 与 null 不同,但使用较弱的 != 时则不同,因为 JavaScript 在这种情况下会进行一些隐式转换。

null 和 undefined 之间的主要区别在于,undefine 也可以表示尚未分配的内容。

                            undefined   false
(SomeObject.foo)            false        false
(SomeObject.foo != null)    false        true
(SomeObject.foo !== null)   true         true
(SomeObject.foo != false)   true         false
(SomeObject.foo !== false)  true         false

这取自 此博客

Undefined is different from null when using !== but not when using the weaker != because JavaScript does some implicit casting in this case.

The main difference between null and undefined is that undefined can also mean something which has not been assigned to.

                            undefined   false
(SomeObject.foo)            false        false
(SomeObject.foo != null)    false        true
(SomeObject.foo !== null)   true         true
(SomeObject.foo != false)   true         false
(SomeObject.foo !== false)  true         false

This is taken from this weblog

上课铃就是安魂曲 2024-10-20 04:29:12

问题是你声称看到了差异,但你却没有。举你的例子。实际上应该是:

var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
    for (var i = 1; i < List.length; i+=2) {
        if (id === List[i].getId()) {
            return List[i];
        }
    }
    // returns undefined by default
}

您的算法有缺陷,因为您检查了甚至索引(即使您知道那里什么也没有),并且您还滥用了null作为返回值。

这些类型的函数确实应该返回undefined,因为这意味着:没有这样的数据

而您正是问题的核心。如果您不完全理解 nullundefined 并且有时可能会错误地使用它们,那么您如何确定其他人会正确使用它们?你不能。

然后还有主机对象及其令人讨厌的行为,如果你问我,你最好同时检查两者。事实上,这并没有什么坏处,它可以让您在处理第三方代码或上述的非本机对象时省去一些麻烦。

除了这两种情况,在你自己的代码中,你可以按照@bobince所说的进行操作:

保留未定义作为特殊值,以便在其他语言可能抛出异常时发出信号。

The problem is that you claim to see the difference, but you don't. Take your example. It should really be:

var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
    for (var i = 1; i < List.length; i+=2) {
        if (id === List[i].getId()) {
            return List[i];
        }
    }
    // returns undefined by default
}

Your algorithm is flawed because you check even indexes (even though you know there's nothing there), and you also misuse null as a return value.

These kind of functions should really return undefined because it means: there's no such data

And there you are in the heart of the problem. If you don't fully understand null and undefined and may use them wrongly sometimes, how can you be so sure that others will use it correctly? You can't.

Then there are Host objects with their nasty behavior, if you ask me, you better off checking for both. It doesn't hurt, in fact, it saves you some headaches dealing with third party code, or the aformentioned non-native objects.

Except for these two cases, in your own code, you can do what @bobince said:

Keep undefined as a special value for signalling when other languages might throw an exception instead.

呆萌少年 2024-10-20 04:29:12

何时设置/使用它们...

请注意,没有 return 语句的方法返回未定义,如果您在应该始终返回的方法中使用它,则不应强制将其作为预期响应值,那么它应该在内部表示错误状态。

使用 null 表示有意或不匹配的响应。


As for how/when to check...

undefined、null、0、空字符串、NaN 和 false 通过强制转换将为 FALSE。这些被称为“虚假”值......其他一切都是真的。

最好的选择是强制转换,然后测试有效的异常值...


var something; //undefined

something = !!something; //something coerced into a boolean

//true if false, null, NaN or undefined
function isFalsish(value) {
  return (!value && value !== "" && value !== 0);
}

//get number or default
function getNumber(val, defaultVal) {
  defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
  return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}

数字测试才是真正的问题,因为 true、false 和 null 可以强制转换为数字,而 0 则强制转换为 false。

When to set/use them...

Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.

Use null for an intentional or non-match response.


As for how/when to check...

undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.

Your best bet is coercion then testing for valid exception values...


var something; //undefined

something = !!something; //something coerced into a boolean

//true if false, null, NaN or undefined
function isFalsish(value) {
  return (!value && value !== "" && value !== 0);
}

//get number or default
function getNumber(val, defaultVal) {
  defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
  return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}

Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.

止于盛夏 2024-10-20 04:29:12

我会将它们视为两个完全不同的值,并检查您知道可能会出现的值。

如果您要检查某些内容是否已被赋予值,请检查undefined

如果您要检查该值是否为“nothing”,请检查“null”

一个稍微人为的示例:

假设您有一系列 ajax 请求,并且您在道德上反对使用回调,因此您有一个超时运行检查其完成情况。

您的支票看起来像这样:

if (result !== undefined){
    //The ajax requests have completed
    doOnCompleteStuff();
    if (result !== null){
        //There is actually data to process
        doSomething(result);
    }
}

tldr;它们是两个不同的值,undefined 表示没有给出任何值,null 表示已经给出了值,但该值是“nothing”。

I would treat them as 2 completely different values, and check for the one you know might occur.

If you're checking to see if something has been given a value yet, check against undefined.

If you're checking to see if the value is 'nothing,' check against 'null'

A slightly contrived example:

Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.

Your check would look something like this:

if (result !== undefined){
    //The ajax requests have completed
    doOnCompleteStuff();
    if (result !== null){
        //There is actually data to process
        doSomething(result);
    }
}

tldr; They are two different values, undefined means no value has been given, null means a value has been given, but the value is 'nothing'.

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