开发者

Javascript NULL Values

I am getting the following javascript error:

'value' is null or not an object

Can someone please let me know what is the best way to check whether an object's value is NULL in javascript as I have been using:

if ((pNonUserID !== "")开发者_如何转开发 || (pExtUserID !== "")){

Is this correct or is there a better way?

Thanks.


You don't have to do that:

var n=null;

if(n)alert('Not null.'); // not shown
if(!n)alert('Is null.'); // popup is shown

Your error implies otherwise:

var n=null;

alert(n.something); // Error: n is null or not an object.

In the case above, something like this should be used:

if(n)alert(n.something);


The !== operator returns true when two variables are not the same object. It doesn't look at the values of the objects at all

To test if something is null:

myVar == null

Your code was testing to see if the variable 'pNonUserId' referred to the same object as "", which can never be true as "" will always be a new instance of the empty string.

As an aside, a test such as:

var n = something();
// do stuff
if (n)
  doSomethingElse();

Is a bad idea. If n was a boolean and false, but you were expecting the if block to test nullify you'll be in for a shock.


if (pNonUserID && pExtUserID)
{
   // neither pNonUserId nor pExtUserID are null here
}

Any Javascript variable automatically evaluates to true when it references an object.

What you were doing are comparisons to empty strings, which are not the same as null.


null, undefined and empty string is consider as false in conditional statement.

so

if(!n) alert("n is null or undefined or empty string"); 
if(n) alert("n has some value");

therefor, inflagranti suggested condition will work perfectly for you

if(pNonUserID && pExtUserID) { 

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜