检查对象属性时与未定义或“未定义”的比较。有什么不同?

问题描述 投票:0回答:2

我在undefined"undefined"之间遇到了这种区别,我正在努力理解它。

我正在检查是否定义了对象中的属性。在第一个例子中,我检查了属性是否未定义。以下所有测试评估为真。无论我使用"undefined"还是undefined都没关系。

var test = {
  x: 1,
  y: 2
};

if (test.x != "undefined") console.log('test.x != "undefined"'); //TRUE
if (test.x !== "undefined") console.log('test.x !== "undefined"'); //TRUE
if (test.x != undefined) console.log('test.x != undefined'); //TRUE
if (test.x !== undefined) console.log('test.x !== undefined'); //TRUE

然后我尝试使用未定义的属性。如果我使用undefined(不是字符串文字)或typeof,它只评估为true。

var test = {
  x: 1,
  y: 2
};

if (test.z === undefined) console.log("test.z === undefined"); //TRUE
if (test.z == undefined) console.log("test.z == undefined"); //TRUE
if (test.z === "undefined") console.log("test.z === 'undefined'"); //FALSE
if (test.z == "undefined") console.log("test.z == 'undefined'"); //FALSE
if (typeof test.z === "undefined") console.log("typeof test.z === 'undefined'"); //TRUE

所以我的问题是:为什么差异(我想我不明白......)。我使用比较“undefined”/ undefined而不是.hasOwnProperty()是不好的做法?

javascript object properties undefined
2个回答
1
投票

undefined"undefined"是不同的价值观。前者是undefined,后者是字符串。

你可能看到的不是x === "undefined"x === undefined,而是typeof x === "undefined"x === undefined。注意typeof。你看到前者(与typeof)的原因之一是历史性的,不再相关,但并非所有原因都是。

假设声明的标识符xundefined没有被遮蔽,这两个语句实际上是相同的,除了第一个必须做更多的工作:

typeof x === "undefined"
x === undefined

但是如果没有声明x,前者将评估为true,后者将因ReferenceError而失败。 (在一般情况下,您可能需要ReferenceError,因为它会提醒您未声明的标识符,但前者有用例。)

但遗憾的是,undefined不是关键词(如null);这是一个全球常数。这意味着undefined可以被遮蔽:

function foo(undefined) {
  var x; // x defaults to the value undefined
  console.log(typeof x === "undefined"); // true
  console.log(x === undefined);          // false?!?!
}
foo(42);

在实践中,如果你发现有人遮住undefined并给它一个除了undefined以外的值,那就把它们带回去用湿面条拍打他们的头部和肩膀,直到他们看到感觉。但...

从历史上看,很多年前,undefined值在一个窗口中的问题不是===undefined值。因此,如果您的代码可能处理来自不同窗口的值,那么与=== undefined进行比较并不是检查undefined的可靠方法。几年前我检查了所有甚至是模糊的最近的浏览器,这不是一个问题(我怀疑它没有那么久)。


1
投票

当您检查"undefined"(在引号中)时,您正在检查值为"undefined"的字符串。

而当您检查undefined时,则检查属性或变量是否已定义。因此,您可以使用它来检查属性是否已定义。

© www.soinside.com 2019 - 2024. All rights reserved.