判断undefined时if/else if语句为何抛出undefined错误?
关于判断undefined时抛出错误的问题解答
1. 为什么判断变量是否为undefined时,if语句会抛出错误?
这种情况几乎都是因为你要判断的目标本身不存在,导致JS引擎找不到它:
- 如果是直接判断一个未声明的变量,比如
if (x === undefined),JS会抛出ReferenceError,因为x从来没被定义过。这时候应该用typeof x === 'undefined',typeof对未声明的变量不会报错,只会返回字符串'undefined'。 - 如果是判断对象的嵌套属性,比如
obj.prop === undefined,但obj本身是undefined或null,那访问obj.prop时就会抛出Cannot read properties of undefined的错误——你得先确保上层的obj存在,才能去读它的属性。
2. 为什么else if判断location[0].properties !== undefined会报错?
核心问题出在你跳过了对location[0]的存在性检查!
比如如果location是空数组、或者location本身是undefined,那location[0]就是undefined,这时候你直接访问location[0].properties,JS就会报错:无法读取undefined的properties属性,根本轮不到你判断它是不是undefined。
解决办法
你需要逐层检查上层对象是否存在,或者用可选链简化判断:
- 方案一(传统写法,兼容旧环境):
if(icon){ dv.find(".mobCol>.image").html(generateIcon(icon)); } else if (location && location[0] && location[0].properties !== undefined){ dv.find(".mobCol>.image").html(/* 你的代码 */); } else { // 当icon不存在,且location[0].properties是undefined时进入这里 } - 方案二(ES2020+可选链,更简洁):
if(icon){ dv.find(".mobCol>.image").html(generateIcon(icon)); } else if (location?.[0]?.properties !== undefined){ dv.find(".mobCol>.image").html(/* 你的代码 */); } else { // 目标分支 }
另外提醒一句:如果你希望当location[0].properties是undefined时进入else分支,那当前的else if条件是对的——只有当properties不是undefined时才会进这个分支,否则进入else。但前提是你得先解决前面的层级访问报错问题,不然代码执行到else if就中断了,根本到不了else。
内容的提问来源于stack exchange,提问作者Caitlyn Daly
相关产品推荐
相关产品推荐

