何时检查undefined以及何时检查null [英] When to check for undefined and when to check for null

查看:133
本文介绍了何时检查undefined以及何时检查null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[Bounty Edit]

我在寻找一个很好的解释,你应该设置/使用 null undefined 以及您需要检查的位置。基本上这两种常见做法是什么,并且可以在通用可维护代码中单独处理它们?

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?

我什么时候可以安全地检查 == = null ,安全检查 === undefined 我何时需要检查 == null

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

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

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

我有各种格式的检查

if(someObj == null) if(someObj!= null)检查null和undefined。我想将所有这些更改为 === undefined === null 但我不确定如何保证它只会是两者之一而不是两者之一。

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.

你应该在哪里使用支票 null 你应该在哪里使用支票 undefined

Where should you use checks for null and where should you use checks for 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 或 undefined 我不知道哪个是正确的。

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

Are在任何情况下你必须检查 null undefined ,因为你别无选择?

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

推荐答案

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

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 如果没有找到元素,则返回 null

document.getElementById returns null if no elements are found.

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

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

你永远不必检查 undefined null (除非您汇总来自可能返回null的源的数据,以及可能返回undefined的源)。

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).

我建议你避免 null ;使用 undefined

这篇关于何时检查undefined以及何时检查null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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