Javascript NULL 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5486218/
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
Javascript NULL Values
提问by tonyf
I am getting the following javascript error:
我收到以下 javascript 错误:
'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:
有人可以让我知道在 javascript 中检查对象的值是否为 NULL 的最佳方法是什么,因为我一直在使用:
if ((pNonUserID !== "") || (pExtUserID !== "")){
Is this correct or is there a better way?
这是正确的还是有更好的方法?
Thanks.
谢谢。
回答by Christian
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);
回答by Royce
The !== operator returns true when two variables are not the same object. It doesn't look at the values of the objects at all
当两个变量不是同一个对象时,!== 运算符返回 true。它根本不看对象的值
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.
您的代码正在测试变量“pNonUserId”是否引用与“”相同的对象,这永远不会为真,因为“”将始终是空字符串的新实例。
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.
是个坏主意。如果 n 是一个布尔值和 false,但您期望 if 块测试无效,您会感到震惊。
回答by neeraj
null, undefined and empty string is consider as false in conditional statement.
null、undefined 和空字符串在条件语句中被认为是假的。
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
因此,inflagranti 建议的条件将非常适合您
if(pNonUserID && pExtUserID) {
}
回答by Janick Bernet
if (pNonUserID && pExtUserID)
{
// neither pNonUserId nor pExtUserID are null here
}
Any Javascript variable automatically evaluates to true when it references an object.
任何 Javascript 变量在引用对象时都会自动评估为 true。
What you were doing are comparisons to empty strings, which are not the same as null.
您所做的是与空字符串的比较,这与 null 不同。