简体   繁体   English

obj =='未定义'或obj ==='未定义'或obj ==空或全部

[英]obj == 'undefined' OR obj === 'undefined' OR obj == null OR ALL

I am always unsure about which one is correct and which ones to use. 我始终不确定哪个是正确的,以及使用哪个。

Usually I do (obj == null) check. 通常我会(obj == null)检查。 I thought its better to just ask. 我认为最好问一下。

Which one of the following shall I use: 我应使用以下哪一项:

  if (obj == null) {
        alert('obj is null');
  }

OR 要么

  if (obj == null || obj == 'undefined') {
        alert('obj is null or undefined');
  }

OR 要么

  if (obj == null || obj == undefined) {
        alert('obj is null or undefined');
  }

OR 要么

  if (obj == null || obj === 'undefined') {
        alert('obj is null or undefined');
  }

Which one is better and do we really need to check for undefined ? 哪个更好, 我们真的需要检查未定义的吗?

Just do 做就是了

if (obj == null) {

That'll check for both null and undefined . 这将检查nullundefined


To the confused downvoters, using the == null will simultaneously check for null and undefined , but no other "falsey" values. 对于困惑的投票者,使用== null将同时检查nullundefined ,但不检查其他“ falsey”值。

The typeof foo === "undefined" syntax actually causes more bugs than it fixes. typeof foo === "undefined"语法实际上导致的错误多于其修复的错误。 Like these... 像这些...

typeof foo === undefined     // common bug

foo === "undefined"          // common bug

typeof foo === "undefnied"   // common bug

These are very common bugs, and are reasons to not use this syntax. 这些是非常常见的错误,也是使用此语法的原因。


Here are the cases for which beginners are told to use that syntax... 在这种情况下,初学者被告知要使用该语法...

  • undefined may have been redefined undefined可能已被重新定义

  • your variable may be undeclared, causing a ReferenceError 您的变量可能未声明,从而导致ReferenceError


Here are the reasons that those aren't very good reasons 这是那些不是很好的原因的原因

  • the global undefined can not be redefined in modern browsers, so it's a non-issue. 全局undefined在现代浏览器中无法重新定义,因此这不是问题。 And even if it does get redefined, then something is terribly wrong, and needs to be fixed either way. 即使重新定义它,也还是存在一些严重错误,需要以任何一种方式进行修复。 If you hide the issue, you'll never be able to fix it. 如果您隐藏该问题,将永远无法修复它。

  • If a developer is trying to use an undeclared local variable, that means there's a bug in the code, and the ReferenceError should be seen as a desirable warning, not as something to be hidden. 如果开发人员尝试使用未声明的局部变量,则意味着代码中存在错误,并且应该将ReferenceError视为理想的警告,而不是要隐藏的东西。

  • If a developer is trying to use an undeclared global variable that can't be known before hand, it's safer to check for the variable as a property on the window object than to use the unsafe typeof foo === "undefined" syntax. 如果开发人员尝试使用事先无法知道的未声明的全局变量,则将变量作为window对象上的属性进行检查比使用不安全的typeof foo === "undefined"语法更为安全。


And yes, there is a type distinction between null and undefined , so both need to be checked. 是的,在nullundefined之间存在类型区别,因此都需要进行检查。 The == operator performs a type coercive algorithm when the types don't match. 当类型不匹配时, ==运算符将执行类型强制性算法。 That's why you can use == null to check for both. 这就是为什么您可以使用== null进行检查的原因。

You've identified four tests: 您已经确定了四个测试:

if (obj == null)
if (obj == null || obj == 'undefined')
if (obj == null || obj == undefined)
if (obj == null || obj === 'undefined')

Of these, the first and third behave identically. 其中,第一和第三行为相同。 ( obj == null will evaluate to true if obj is undefined.) * The second and fourth do not do what you want at all, because the test will succeed if obj is the string 'undefined' (as well as when obj is undefined, thanks to how obj == null behaves). (如果obj未定义,则obj == nulltrue 。) *第二和第四个都不执行您想要的操作,因为如果obj字符串 'undefined' (以及obj未定义时),测试将成功,这要归功于obj == null行为)。

As to whether you need to test for undefined, that depends on whether you need to distinguish between undefined values and null values. 至于是否需要测试未定义,取决于您是否需要区分未定义值和空值。 In most applications, you do not need to do that. 在大多数应用程序中,您不需要这样做。 If you do need to do that, you should be using obj === null and obj === undefined . 如果确实需要这样做,则应使用obj === nullobj === undefined

If you need to safeguard against undeclared variables, then you can use: 如果需要防止未声明的变量,则可以使用:

if (typeof obj === 'undefined')

but in all but the most unusual situations, you should know in a given context whether a variable has been declared. 但除了最不常见的情况外,您都应该在给定的上下文中知道是否已声明变量。

* However, obj === null will evaluate to false if obj is undefined. * 但是,如果obj未定义,则obj === null将得出false

undefined is a word that means not defined . undefined是一个单词,表示not defined

null is an object null是一个对象

Let see this code 让我们看一下这段代码

function saySomething(thing) {
    if(thing === undefined) {
        sayRandomThing();
    }else {
        sayThat(thing);
    }
}

In this case I would check if the argument is given or not or, in other words, if the argument is defined or not. 在这种情况下,我将检查是否给定参数,或者换句话说,是否定义了参数。

Note that the variable name thing is declared, but it's not defined. 请注意,已声明变量名称thing ,但未定义它。 So in this case thing === undefined is enough and you don't need to do more verbose typeof thing === "undefined" . 因此,在这种情况下, thing === undefined就足够了,您不需要做更多冗长的typeof thing === "undefined"

There is no reason to use the word null . 没有理由使用单词null Because null is an object and it have nothing to do with our thing . 因为null是一个对象,它与我们的thing无关。

Just another note. 只是另一个说明。 typeof thing === "undefined" is needed when effectly you don't know if the variable is declared. 当实际上不知道是否声明了变量时,需要typeof thing === "undefined" But, as documentation say : 但是,正如文档所说

However, this kind of technique should be avoided . 但是, 应避免这种技术 JavaScript is a statically scoped language, so knowing if a variable is defined can be read by seeing whether it is defined in an enclosing context. JavaScript是一种静态作用域语言,因此可以通过查看变量是否在封闭的上下文中进行定义来了解是否定义了变量。 The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the in operator, for instance) 唯一的例外是全局范围,但是全局范围绑定到全局对象,因此可以通过检查全局对象上属性的存在来检查全局上下文中变量的存在(使用in运算符,例如)

When should I use null ? 什么时候应该使用null

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null 来自https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/null

In APIs, null is often retrieved in place where an object can be expected but no object is relevant. 在API中,通常会在期望有对象但没有对象相关的地方检索null。

null is an object. null是一个对象。 Javascript core use null when a function should returns an object or an array, but in some case should tell us an "object not found" (different case of an empty object {} that means: I've found the object, it's empty). 当函数应返回对象或数组,但在某些情况下应告诉我们“未找到对象”(不同情况下的空对象{}表示:我已找到对象,它为空),因此Javascript核心使用null It's the case of method match for example. 例如,方法match就是这种情况。

var matches = "My awesome string".match("don't match anything");

console.log(matches === null); // true

In your script, you know, as developer, what type should be the variable. 在您的脚本中,作为开发人员,您知道变量应该是什么类型。 And you should know which condition you should use. 并且您应该知道应该使用哪种条件。 Remembering: 记住:

  • If you don't know if the variable is declared or not, use if(typeof varName === "undefined") before other checks. 如果您不知道是否声明了变量,请在其他检查之前使用if(typeof varName === "undefined")
  • If you don't know if the variable is defined or not, use if(varName === undefined) before other checks. 如果您不知道变量是否已定义 ,请在其他检查之前使用if(varName === undefined)
  • If you know if the variable is defined and it's an object, check if is null with if(varName === null) 如果您知道变量是否已定义并且是对象,请使用if(varName === null)检查是否为null

The strict equality operator ( === ) is needed because varName == undefined also checks whether varName is null 需要严格相等运算符( === ),因为varName == undefined还会检查varName是否为null

Please use the following if you want to check for the existence of the object in question and prevent various JS erorrs: 如果要检查是否存在相关对象并防止各种JS错误,请使用以下内容:

if (typeof(abc) === 'undefined') {
    console.log('not defined');
}

jsFiddle proving the usefulness: http://jsfiddle.net/tJyfg/1/ jsFiddle证明其有用性: http : //jsfiddle.net/tJyfg/1/

If you're looking to check a global variable, then the following will do the trick without using typeof() (works for all objects as well)... 如果您要检查全局变量,则可以使用以下方法而无需使用typeof() (同样适用于所有对象)...

if (!window.abc) {
  console.log('not defined');
}

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

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