当前位置: 代码迷 >> JavaScript >> Javascript NULL值
  详细解决方案

Javascript NULL值

热度:76   发布时间:2023-06-05 14:08:41.0

我收到以下javascript错误:

'value' is null or not an object

有人可以让我知道在我使用的javascript中检查对象的值是否为NULL的最佳方法是什么:

if ((pNonUserID !== "") || (pExtUserID !== "")){

这是正确的还是有更好的方法?

谢谢。

你不必这样做:

var n=null;

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

你的错误暗示:

var n=null;

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

在上面的例子中,应该使用这样的东西:

if(n)alert(n.something);

当两个变量不是同一个对象时,!==运算符返回true。 它根本不会查看对象的值

要测试某些东西是否为null:

myVar == null

您的代码正在测试以查看变量'pNonUserId'是否引用与“”相同的对象,这永远不会为真,因为“”将始终是空字符串的新实例。

另外,测试如下:

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

是个坏主意。 如果n是布尔值而且是假的,但是你期望if块测试无效,那么你将会感到震惊。

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

任何Javascript变量在引用对象时自动计算为true。

你正在做的是与空字符串的比较,这些字符串与null不同。

null,undefined和empty string在条件语句中被视为false。

所以

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

因此,inflagranti建议条件将完美适合您

if(pNonUserID && pExtUserID) { 

}
  相关解决方案