gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:56:34 25 4
gpt4 key购买 nike

[赏金编辑]

当您应该设置/使用 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?
}

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

是否有任何情况下您必须同时检查 nullundefined因为你别无选择?

最佳答案

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

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 ;使用 undefined .

关于javascript - 何时检查未定义以及何时检查 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4748429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com