假设我在Java中访问一个名为jso的JavaScript对象,并且我使用以下语句来测试它是否为null
if (jso == null)
Run Code Online (Sandbox Code Playgroud)
但是,当jso包含一些空值时,这个语句似乎返回true,这不是我想要的.
是否有任何方法可以区分空JavaScript对象和包含一些空值的JavaScript对象?
谢谢
Kir*_*oll 16
要确定目标引用是否包含具有空值的成员,您必须编写自己的函数,因为没有开箱即用的函数可以为您执行此操作.一个简单的方法是:
function hasNull(target) {
for (var member in target) {
if (target[member] == null)
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
毋庸置疑,这只会深入一级,因此如果其中一个成员target包含另一个具有空值的对象,则仍将返回false.作为用法的例子:
var o = { a: 'a', b: false, c: null };
document.write('Contains null: ' + hasNull(o));
Run Code Online (Sandbox Code Playgroud)
将打印出来:
包含null:true
相反,以下内容将打印出来false:
var o = { a: 'a', b: false, c: {} };
document.write('Contains null: ' + hasNull(o));
Run Code Online (Sandbox Code Playgroud)
这仅供您参考.不要投票.
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27287 次 |
| 最近记录: |