开发者

This if statement should not detect 0; only null or empty strings

Using JavaScript, how do I NOT detect 0, but other开发者_如何学Pythonwise detect null or empty strings?


If you want to detect all falsey values except zero:

if (!foo && foo !== 0) 

So this will detect null, empty strings, false, undefined, etc.


From your question title:

if( val === null || val == "" )

I can only see that you forgot a = when attempting to strict-equality-compare val with the empty string:

if( val === null || val === "" )

Testing with Firebug:

>>> 0 === null || 0 == ""
true

>>> 0 === null || 0 === ""
false

EDIT: see CMS's comment instead for the explanation.


function isNullOrEmptyString(val) {
  return (val === null || val === '');
}

console.log({
"isNullOrEmptyString(0)": isNullOrEmptyString(0), 
"isNullOrEmptyString('')": isNullOrEmptyString(""), 
"isNullOrEmptyString(null)": isNullOrEmptyString(null),
"isNullOrEmptyString('something')": isNullOrEmptyString("something"),
});


I know this might be a too late answer but it might help someone else.

If I understand you correctly you want the below statement to exclude the 0:

 if(!value) {
    //Do things
 }

I think the easiest way to do this is to write the statement like this:

if(!value && value !== 0) {
  //Do things
}

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜