Javascript 如何检查javascript对象是否包含空值或其本身为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7936480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:07:27  来源:igfitidea点击:

how to check if a javascript object contains null value or it itself is null

javascript

提问by mpang

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

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

if (jso == null)

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

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

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

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

Thanks

谢谢

回答by Kirk Woll

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;
}

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

不用说,这只会深入一层,所以如果其中一个成员target包含另一个具有空值的对象,这仍然会返回 false。作为用法示例:

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

Will print out:

会打印出来:

Contains null: true

包含空值:true

In contrast, the following will print out false:

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

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

回答by Samuel Liew

This is just for your reference. Do not upvote.

这仅供您参考。不要点赞。

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

http://jsfiddle.net/3JZfT/3/

http://jsfiddle.net/3JZfT/3/

回答by Niloct

Try an extra =

尝试一个额外的 =

if (jso === null)