简体   繁体   English

比较JavaScript中的未定义值

[英]Comparing undefined value in JavaScript

I have an object whose value may be undefined sometimes. 我有一个其值有时可能不确定的对象。 So is it possible / valid / good practice to test it with an if case like below : 因此,是否有可能/有效/好的做法是使用以下if情况进行测试:

if(params === undefined)  
{  
    alert("sound." + params);  
}  

If not, why can't we do it? 如果没有,我们为什么不能这样做?

As of now, it is working fine. 截至目前,它运行良好。 Yet, I would like to know if it can go wrong anytime? 但是,我想知道它是否随时可能出错?

Thanks 谢谢

Since in theory undefined can be redefined (at least pre-JS 1.8.5), it's better to use 由于理论上可以重新定义undefined (至少在JS 1.8.5之前),因此最好使用

if (typeof params === 'undefined')

This also works without throwing an error if params is not a known variable name. 如果params不是已知的变量名,这也不会抛出错误。

Use typeof varName for safer usage:- 使用typeof varName可以更安全地使用:-

This will not throw any error if params is not a variable declared anywhere in your code. 如果params不是代码中任何地方声明的变量,则不会引发任何错误。

 if(typeof params  === "undefined")
   {
       //it is not defined
   }

 if(params === undefined)   //<-- This will fail of you have not declared the variable 
        //param. with error "Uncaught ReferenceError: params is not defined "
 {
 }

Refer Undefined 参考未定义

The typeof answers are good, here's a bit extra. typeof运算答案是好的,这里有一个画龙点睛的效果。 To me, this is a case where you need to explain what you are doing with params . 对我来说,这是您需要解释params正在做什么的情况。 If you are doing say: 如果您在说:

function foo(paramObject) {
  // determine if a suitable value for paramObject has been passed
}

then likely you should be testing whether paramObject is an object, not whether it has some value other than undefined . 那么您可能应该测试paramObject是否是一个对象,而不是它是否具有除undefined以外的其他值。 So you might do: 因此,您可以这样做:

  if (typeof paramObject == 'object') {
    // paramObject is an object
  }

but you still don't know much about the object, it could be anything (including null ). 但是您仍然对该对象不太了解,它可以是任何东西(包括null )。 So generally you document the object that should be passed in and just do: 因此,通常您会记录应传递的对象并执行以下操作:

  if (paramObject) {
    // do stuff, assuming if the value is not falsey, paramObject is OK
  }

now if it throws an error, that's the caller's fault for not providing a suitable object. 现在,如果它抛出错误,那就是调用者没有提供合适对象的错误。

The corollary is that all variables should be declared so that the test doesn't throw an error (and you don't need to use typeof , which is one of those half useful operators that promises much but doesn't deliver a lot). 结果是,应该声明所有变量,以使测试不会引发错误(并且您不需要使用typeof ,后者是半有用的运算符之一,可以承诺很多但不能提供很多东西)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM