如何检查javascript对象是否包含null值或它本身是否为null [英] how to check if a javascript object contains null value or it itself is null

查看:62
本文介绍了如何检查javascript对象是否包含null值或它本身是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Java中访问一个名为jso的JavaScript对象,我正在使用以下语句来测试它是否为null

Say I'm accessing a JavaScript Object called jso in Java and I'm using the following statement to test if it's null

if (jso == null)

然而,当jso包含一些时,此语句似乎返回true null值,这不是我想要的。

However, this statement seems to return true when jso contains some null values, which is not what I want.

是否有任何方法可以区分空JavaScript对象和包含一些空值的JavaScript对象?

Is there any method that can distinguish between a null JavaScript Object and a JavaScript Object that contains some null values?

谢谢

推荐答案

确定目标参考是否包含null的成员价值,你必须编写自己的功能,因为没有现成的功能为你做这件事。一种简单的方法是:

To determine whether the target reference contains a member with a null value, you'll have to write your own function as none exist out of the box to do this for you. One simple approach would be:

function hasNull(target) {
    for (var member in target) {
        if (target[member] == null)
            return true;
    }
    return false;
}

毋庸置疑,这只是一个深度,所以如果其中一个 target 上的成员包含另一个具有空值的对象,这仍将返回false。作为一个例子:

Needless to say, this only goes one level deep, so if one of the members on target contains another object with a null value, this will still return false. As an exmaple of usage:

var o = { a: 'a', b: false, c: null };
document.write('Contains null: ' + hasNull(o));

将打印出来:


包含null:true

Contains null: true

相反,以下内容将打印出 false

In contrast, the following will print out false:

var o = { a: 'a', b: false, c: {} };
document.write('Contains null: ' + hasNull(o));

这篇关于如何检查javascript对象是否包含null值或它本身是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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