提问人:mpang 提问时间:10/29/2011 最后编辑:Cammpang 更新时间:10/27/2022 访问量:40817
如何检查 JavaScript 对象是否包含 null 值或它本身是否为 null
how to check if a javascript object contains null value or it itself is null
问:
假设我正在访问 Java 中名为 jso 的 JavaScript 对象,并且我正在使用以下语句来测试它是否为 null
if (jso == null)
但是,当 jso 包含一些 null 值时,此语句似乎返回 true,这不是我想要的。
是否有任何方法可以区分空 JavaScript 对象和包含一些空值的 JavaScript 对象?
谢谢
答:
2赞
Niloct
10/29/2011
#1
尝试额外的=
if (jso === null)
6赞
Samuel Liew
10/29/2011
#2
这仅供参考。不要投赞成票。
var jso;
document.writeln(typeof(jso)); // 'undefined'
document.writeln(jso); // value of jso = 'undefined'
jso = null;
document.writeln(typeof(jso)); // null is an 'object'
document.writeln(jso); // value of jso = 'null'
document.writeln(jso == null); // true
document.writeln(jso === null); // true
document.writeln(jso == "null"); // false
19赞
Kirk Woll
10/29/2011
#3
若要确定目标引用是否包含具有 null 值的成员,必须编写自己的函数,因为没有现成的函数可以执行此操作。一个简单的方法是:
function hasNull(target) {
for (var member in target) {
if (target[member] == null)
return true;
}
return false;
}
毋庸置疑,这只会深入一级,因此,如果其中一个成员包含另一个具有 null 值的对象,则仍将返回 false。作为用法的示例:target
var o = { a: 'a', b: false, c: null };
document.write('Contains null: ' + hasNull(o));
将打印出:
包含 null: true
相反,以下内容将打印出来:false
var o = { a: 'a', b: false, c: {} };
document.write('Contains null: ' + hasNull(o));
1赞
Abiola Aribisala
10/27/2022
#4
这是一个非常糟糕的方法
if (Object.values(jso).includes(null)) {
// condition
}
else{
// condition
}
评论
===
===