何时检查undefined以及何时检查null

Ray*_*nos 20 javascript null undefined

[赏金编辑]

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

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

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

我有各种格式的检查

if (someObj == null)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?
}
Run Code Online (Sandbox Code Playgroud)

这只是其中的一个,我可以同时使用例如null或者undefined,我不知道哪个是正确的.

有没有必须检查两者的情况null,undefined因为你别无选择?

Mat*_*att 11

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

function foo () {

};

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

//foo() === undefined && bar[100] === undefined && baz.something === undefined
Run Code Online (Sandbox Code Playgroud)

document.getElementByIdnull如果没有找到元素则返回.

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

// el === null || el instanceof HTMLElement
Run Code Online (Sandbox Code Playgroud)

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

我建议你避免null; 用undefined.


Tim*_*own 5

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

我建议您确定您确切地知道您正在测试的变量或属性可能的值,并明确且有信心地测试这些值.要测试null,请使用foo === null.为了进行测试undefined,我建议typeof foo == "undefined"在大多数情况下使用 ,因为undefined(不像null)不是保留字,而是可以改变的全局对象的简单属性,以及我最近在这里写的其他原因:variable == = undefined与typeof变量==="undefined"