处理对象undefined属性时持续报错的技术咨询
兄弟,我一眼就看出你踩了JS里一个超常见的坑:你只盯着Location属性的判断,但忽略了**choice这个父对象本身可能是null或者undefined**!
为什么你之前的代码都会报错?
不管你写typeof choice.Location == "undefined"还是choice.Location == undefined,只要choice本身是null或者undefined,JS都会直接抛出类似Cannot read properties of undefined (reading 'Location')的错误——因为你根本没法从一个不存在的对象上读取属性,代码连判断逻辑都走不到。
就连你补充的那段代码也有漏洞:typeof choice == "undefined"只能判断choice是undefined的情况,但如果choice是null,typeof choice会返回"object"(这是JS的历史遗留bug),所以代码会走到else if (choice.Location)这一步,照样报错。
正确的处理方式
你需要先确保choice本身存在,再去检查它的属性,这里给你两种靠谱的写法:
1. 可选链操作符(推荐,ES2020+支持)
这是最简洁的写法,会自动短路:如果choice是null/undefined,直接返回undefined,不会报错:
// 检查Location是否不存在(包括choice本身不存在的情况) if (!choice?.Location) { // 这里写你的处理逻辑 } // 如果你需要精确判断Location为undefined(排除0、''等假值) if (choice?.Location === undefined) { // 处理逻辑 }
2. 传统兼容写法(适配旧环境)
如果你的项目需要兼容不支持可选链的旧浏览器,就用嵌套判断,先覆盖choice为null和undefined的情况:
// 先判断choice是否为null/undefined,再检查Location属性 if (choice == null || typeof choice.Location === "undefined") { // 处理逻辑 }
小提醒
如果你担心Location可能是0、''、false这类“假值”,别直接用!choice?.Location判断,要精确判断它是否为undefined或者null,避免误判。
内容的提问来源于stack exchange,提问作者sacora

