Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

how to check if a javascript object contains null value or it itself is 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)

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

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Will print out:

Contains null: true

In contrast, the following will print out false:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...