Javascript 未定义条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7231873/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:24:30  来源:igfitidea点击:

Javascript undefined condition

javascript

提问by David Laberge

Could somebody explain to me the difference between if(obj.x == undefined)and if(typeof obj.x == 'undefined')

有人可以向我解释if(obj.x == undefined)if(typeof obj.x == 'undefined')

In some context the first one works fine, but in other I need to use the second way.

在某些情况下,第一个工作正常,但在其他情况下我需要使用第二种方式。

Questions

问题

1 - What is the difference between the two condition?

1 - 这两种情况有什么区别?

2 - Is there a best practice?

2 - 有最佳实践吗?

回答by jondavidjohn

The best practice is to not just check the truthinessbut the strict equality

最佳实践是不仅检查真实性,而且检查严格相等

example

例子

if (obj.x === undefined) {}

this use to be an issue because undefined(a global property) use to be writable, as of 1.8.5 is is non-writable, providing you with a secure comparison in ES5 spec environments.

这个使用是一个问题,因为undefined(全局属性)使用是可写的,从 1.8.5 开始是不可写的,为您提供在 ES5 规范环境中的安全比较。

per MDN

每个MDN

回答by Tim Down

The two would usually be equivalent if you replaced the equality operator ==with the strict equality operator ===. So obj.x === undefinedand typeof obj.x == "undefined"are usually equivalent.

如果==用严格相等运算符替换相等运算符,则两者通常是等效的===。所以obj.x === undefinedtypeof obj.x == "undefined"通常是等价的。

However, in pre-ECMAScript 5 environments (which still acount for the majority of web requests, in general), undefinedis a writable property of the global object, meaning that undefinedmay be used as variable name or the global property may be assigned a different value. ECMAScript 5 makes the global property read-only, but even then, undefinedmay still be used as variable name within a function, meaning that the typeofcheck is always safer.

但是,在 ECMAScript 5 之前的环境中(通常仍然占大多数 Web 请求),undefined是全局对象的可写属性,这意味着它undefined可以用作变量名或全局属性可以分配不同的值. ECMAScript 5 使全局属性只读,但即便如此,undefined仍然可以在函数中用作变量名,这意味着typeof检查总是更安全。

One further point in favour of typeofis that it may be used to check for a variable that may not have been declared whereas a direct comparison will throw a ReferenceErrorif the variable has not been declared. For example:

支持的另一点typeof是它可用于检查可能尚未声明的变量,而ReferenceError如果变量尚未声明,则直接比较将抛出 a 。例如:

typeof foo == "undefined" // true
foo === undefined // ReferenceError

However, this is an unusual and not generally helpful thing to be doing.

然而,这是一件不寻常且通常没有帮助的事情。

回答by 6502

The two are not equivalent tests because of the quite convoluted handling of special values by javascript. In the specific

由于 javascript 对特殊值的处理非常复杂,因此这两者不是等效的测试。在具体

undefined == null

is true, but typeof undefinedis "undefined"while typeof nullis "object".

是真的,但是typeof undefined"undefined"whiletypeof null"object"

The rules for those special values are quite complex and IMO illogical, so I think there's no "general rule". What you may find are common forms, for example

这些特殊值的规则非常复杂,而且 IMO 不合逻辑,所以我认为没有“一般规则”。你可能会发现一些常见的形式,例如

var value = obj.x || default_value;

that can be used if you're sure that obj will never be undefinedor null(because in that case an exception would be thrown) and assuming that 0, NaNor an empty string should be considered as if no value was provided (because they're all "logically false" values). An empty array or an empty javascript object instead are considered "logically true".

如果您确定 obj 永远不会是undefinednull(因为在这种情况下会抛出异常)并假设0,NaN或空字符串应该被视为好像没有提供任何值(因为它们都是“逻辑错误”值)。一个空数组或一个空的 javascript 对象被认为是“逻辑上正确的”。

Why is it that way? Why does (null).xthrow an exception when nullaccording to typeofis apparently an object and searching for a non-existent field in an object normally returns undefinedinstead?

为什么会这样?为什么(null).xnull根据typeof显然是一个对象并且在对象中搜索不存在的字段通常会返回时抛出异常undefined

I've no idea.

我不知道。

I never tried to find a logic in all those strange rules. I'm not actually even 100% sure there's one.

我从未试图在所有这些奇怪的规则中找到逻辑。我什至不能 100% 确定有一个。

My suggestion is just to study and experiment with them.

我的建议只是研究和试验它们。

回答by Pankaj Chauhan

The main difference of these two condition is typeof

这两个条件的主要区别是 typeof

The typeofoperator is used to get the data type (returns a string) of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type.

typeof运算符用于获取其操作数的数据类型(返回一个字符串)。操作数可以是文字或数据结构,例如变量、函数或对象。运算符返回数据类型。

if (typeof obj.x === 'undefined') {
    txt = "x is undefined";
  } else {
    txt = "x is defined";
  }

回答by i100

second is easier and faster than first. First requires additional setup, definition of undefined and check wheter obj contains x as a property or method. second makes the check whether obj.x has been whenever defined and assigned

第二个比第一个更容易和更快。首先需要额外的设置,定义 undefined 并检查 obj 是否包含 x 作为属性或方法。second 检查 obj.x 是否已在定义和分配时

PS.: undefined will be evaluated to null so obj.x == undefined is equivalent to obj.x == null

PS.: undefined 将被评估为 null 所以 obj.x == undefined 等价于 obj.x == null

回答by Baz1nga

the best way to test for conditionality isusing obj.xthis checks for both null-ability and undefined .

测试条件的最佳方法是使用obj.xthis 检查可空性和 undefined 。

Thus

因此

if(!obj.x) 
{
  alert(obj.x);
}
else   
{
  alert("obj.x is null or undefined");  //obj.x is null or undefined or any false value which is what you want. like obj.x is false or 0
}