如何检查JavaScript中的对象属性是否未定义?
当前回答
ECMAScript 10引入了一个新特性——可选链接,只有当对象定义为如下时,才可以使用该特性来使用对象的属性:
const userPhone = user?.contactDetails?.phone;
只有在定义了user和contactDetails时,它才会引用phone属性。
裁判。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
其他回答
function isUnset(inp) {
return (typeof inp === 'undefined')
}
如果变量已设置,则返回false;如果未定义,则返回true。
然后使用:
if (isUnset(var)) {
// initialize variable here
}
if (somevariable == undefined) {
alert('the variable is not defined!');
}
您也可以将其转换为函数,如下所示:
function isset(varname){
return(typeof(window[varname]) != '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中,当输入值完全未定义时,可选参数会起作用。
Object.hasOwnProperty(o,'propertyname');
然而,这并不能通过原型链进行查找。
我不确定将==与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