如何检查JavaScript中的对象属性是否未定义?
当前回答
Lodash库中有几个小助手:
isUndefined-检查值是否未定义。
_.isUndefined(undefined) // => true
_.isUndefined(null) // => false
has-检查对象是否包含属性
const object = { 'a': { 'b': 2 } }
_.has(object, 'a.b') // => true
_.has(object, 'a.c') // => false
其他回答
我认为这个问题有很多不正确的答案。与通常的看法相反,“undefined”在JavaScript中不是关键字,实际上可以为其赋值。
正确的代码
执行此测试的最可靠方法是:
if (typeof myVar === "undefined")
这将始终返回正确的结果,甚至可以处理未声明myVar的情况。
退化代码。不要使用。
var undefined = false; // Shockingly, this is completely legal!
if (myVar === undefined) {
alert("You have been misled. Run away!");
}
此外,myVar==undefined将在未声明myVar的情况下引发错误。
在《探索JavaScript中的空和未定义的深渊》一文中,我看到Undercore.js等框架使用了这个函数:
function isUndefined(obj){
return obj === void 0;
}
有一种非常简单的方法。
您可以使用可选链接:
x = {prop:{name:"sajad"}}
console.log(x.prop?.name) // Output is: "sajad"
console.log(x.prop?.lastName) // Output is: undefined
or
if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error
您甚至可以对函数或数组使用可选的链接。
截至2020年年中,这一点尚未得到普遍实施。查看文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
同样的事情也可以写得更短:
if (!variable){
// Do it if the variable is undefined
}
or
if (variable){
// Do it if the variable is defined
}
在JavaScript中,存在null和undefined。它们有不同的含义。
undefined表示变量值尚未定义;不知道值是多少。null表示变量值被定义并设置为null(没有值)。
Marijn Haverbeke在他的免费在线书《Eloquent JavaScript》(我的重点)中写道:
还有一个类似的值null,其含义是“此值已定义,但没有值”。undefined和null之间的含义差异主要是学术性的,通常不太有趣。在实际程序中,经常需要检查某个东西是否“有价值”。在这些情况下,可以使用表达式something==undefined,因为即使它们不是完全相同的值,null==undefine也会产生true。
所以,我想最好的检查方法是:
if (something == undefined)
对象财产的工作方式应该相同。
var person = {
name: "John",
age: 28,
sex: "male"
};
alert(person.name); // "John"
alert(person.fakeVariable); // undefined