如何检查JavaScript中的对象属性是否未定义?
当前回答
Use:
要检查属性是否未定义,请执行以下操作:
if (typeof something === "undefined") {
alert("undefined");
}
要检查属性是否未定义,请执行以下操作:
if (typeof something !== "undefined") {
alert("not undefined");
}
其他回答
我在这里为那些希望得到奇怪答案的人提供了三种方法:
函数为Undefined1(val){尝试{值a;}捕获(e){返回/未定义/测试(e.message);}return false;}函数为Undefined2(val){回来val&&val+“”==“未定义”;}函数未定义3(val){常量defaultVal={};return((input=defaultVal)=>input==defaultVal(val);}功能测试(func){console.group(`test start:`+func.name);console.log(func(未定义));console.log(func(null));console.log(函数(1));console.log(函数(“1”));console.log(函数(0));console.log(func({}));console.log(func(函数(){}));console.groupEnd();}测试(isUndefined1);测试(未定义2);测试(未定义3);
未定义1:
尝试获取输入值的属性,并检查错误消息(如果存在)。如果输入值未定义,则错误消息将为Uncaught TypeError:无法读取未定义的属性“b”。
未定义2:
将输入值转换为字符串以与“undefined”进行比较,并确保其为负值。
未定义3:
在JavaScript中,当输入值完全未定义时,可选参数会起作用。
有一种非常简单的方法。
您可以使用可选链接:
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
在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
我不确定将==与typeof一起使用的起源,按照惯例,我在许多库中都使用了它,但typeof运算符返回字符串文本,我们事先就知道了,所以为什么还要对其进行类型检查呢?
typeof x; // some string literal "string", "object", "undefined"
if (typeof x === "string") { // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") { // sufficient
ECMAScript 10引入了一个新特性——可选链接,只有当对象定义为如下时,才可以使用该特性来使用对象的属性:
const userPhone = user?.contactDetails?.phone;
只有在定义了user和contactDetails时,它才会引用phone属性。
裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining