我遇到undefined
和"undefined"
之间的这种差异,我试图理解它。检查对象属性时与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
然后我用这不仅defined.It计算结果为真,如果我使用undefined
(不是字符串文本)或typeof
财产尝试过。
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()
这是不好的做法吗?
这取决于你想要检查的内容。大多数时候,你可以简单地使用像这样的东西:'if(test.x){...}'或'if(!text.z){...}'。这些类型的条件检查很多东西,例如'undefined',* empty string *,'0','null','false'。 – Titus
@Titus:我不想检查它是否存在;下一阶段是switch(),具体取决于属性。 –
在这种情况下,你可以直接写'switch'语句,不需要先检查。 – Titus